1. 程式人生 > >【angularjs指令】簡單的搜尋框實現

【angularjs指令】簡單的搜尋框實現

/***
 *(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);
	}
}])