我有两个元素级指令,一个搜索框和一个搜索结果。我的标记是这样的(简化):
<catalogue-search-box query="{{query}}">
<catalogue-search-results></catalogue-search-results>
我正在尝试从搜索结果指令访问搜索框控制器,但文档表明在指令的 require 属性中,我只能在同一元素或父元素上找到控制器。有没有办法在相邻元素上找到控制器?
我有两个元素级指令,一个搜索框和一个搜索结果。我的标记是这样的(简化):
<catalogue-search-box query="{{query}}">
<catalogue-search-results></catalogue-search-results>
我正在尝试从搜索结果指令访问搜索框控制器,但文档表明在指令的 require 属性中,我只能在同一元素或父元素上找到控制器。有没有办法在相邻元素上找到控制器?
在您发表评论之后,我会这样做:使用一个对象来保存您的所有状态并将其传递给两个指令。演示插件
HTML
<body ng-controller="MySearchController">
<search-box search="mySearch"></search-box>
<search-results search="mySearch"></search-results>
</body>
JS
var search = angular.module('search', []);
//simulated service
search.service('Search', ['$timeout', '$q', function($timeout, $q) {
return {
findByQuery : function(query) {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve([query + ' result1', query + ' result2']);
console.log('resolved query ' + query);
}, 2000);
return deferred.promise;
}
};
}]);
search.controller('MySearchController', ['$scope', function($scope) {
$scope.mySearch = {
query : ''
}
}]);
search.controller('SearchBoxCtrl', ['$scope', 'Search', function($scope, Search) {
$scope.execute = function(search) {
console.log(search);
if(search.query && search.query.length > 3 && !search.running) {
search.running = true;
search.promise = Search.findByQuery(search.query).then(function(val) {
search.results = val;
});
}
};
}]);
search.directive('searchBox', function(){
return {
restrict: 'E',
scope : {
search : '='
},
controller: 'SearchBoxCtrl',
template : '<div ng-hide="search.results">Query: <input type="text" ng-model="search.query" ng-disabled="search.running"></input> <button ng-click="execute(search)" ng-disabled="search.running">Search</button></div>',
replace: 'true'
};
});
search.controller('SearchResultsCtrl', function(){
});
search.directive('searchResults', function(){
return {
restrict: 'E',
scope : {
search : '='
},
controller: 'SearchResultsCtrl',
template : '<div ng-show="search.results"><div ng-repeat="result in search.results">{{result}}</div></div>',
replace: true,
link : function(scope, element, attrs, ctrl){
}
};
});
PS:
自从问题是有某种控制器指令以来,我一直在尝试的一种方法,即
<catalogue-search>
<catalogue-search-box query="{{query}}">
<catalogue-search-results></catalogue-search-results>
</catalogue-search>
然后,我可以在我的 require 语句中使用父 (^) 修饰符访问“控制器指令”。然后,每个指令都可以通过控制器指令相互通信。
这看起来是明智的还是让事情变得过于复杂?