【angularjs指令】简单的搜索框实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a928200728/article/details/53005054

/***
 *(options)是否必填,类型,说明:
 *	(ng)1 , object , angularApp对象
 *
 *(ngScope):
 *	(value)0 , string , 单向绑定的value对象
 *	(searchCall)1 , function , search回掉函数
 *	(keyChangeCall)1 , function , 内容变化回掉函数
 */
define(function(require, exports, module) {
	module.exports = function(param) {
		var options = {};
		if (param.directive) options.ng = param
		else options = param;
		if (!options.ng) return false;

		var domString = [
			"<div class='input-group input-group-sm'>",
			"<span class='input-group-btn'>",
			"<button class='btn btn-primary' type='button' ng-click='searchCall({value:value})'>搜索</button>",
			"</span>",
			"<input type='text' class='form-control' ng-model='value' ng-keyup='keyup($event)'/>",
			"</div>"
		].join("");

		options.ng.directive('stSearch', function() {
			return {
				scope: {
					"searchCall": "&",
					"value": "=",
					"keyChangeCall": "&changeCall"
				},
				restrict: "E",
				template: domString,
				replace: true,
				compile: function(element, attrs, transclude) {
					return function($scope) {
						$scope.$watch('value', function(newValue, oldValue) {
							$scope.keyChangeCall({
								newValue: newValue,
								oldValue: oldValue
							});
						});

						$scope.keyup = function(e) {
							var keycode = window.event ? e.keyCode : e.which;
							if (keycode == 13) {
								$scope.searchCall({
									value: $scope.value
								})
							}
						}
					}
				},
				controller: function($scope) {

				}
			}
		})

		return true;
	}
})

以上代码是基于seajs的简略封装,可以从第17或26行自行拆分

以下为基于seajs的使用方式


js层面引用:

require('js/search')(ng);//在init文件中引用,ng为app对象

HTML层面调用:

<div ng-controller="searchModule">
	<st-search search-call="searchCall(value)" value="value" change-call="keyChangeCall(newValue, oldValue)" class="col-md-4 col-md-offset-4 col-sm-12"></st-search>
</div>


searchModule controller:

ng.controller('searchModule', ["$scope", "$rootScope", function(scope, rootScope) {
	scope.searchCall = function(value) {
		rootScope.$broadcast('searchEvent', value);
	}
	scope.value = "石头web";//初始输入框内容
	scope.keyChangeCall = function() {
		console.log(arguments);
	}
}])

没有更多推荐了,返回首页