我有两个元素级指令,一个搜索框和一个搜索结果。我的标记是这样的(简化):
<catalogue-search-box query="{{query}}">
<catalogue-search-results></catalogue-search-results>
我正在尝试从搜索结果指令访问搜索框控制器,但是文档建议在指令的require属性中我只能在同一元素或父元素上找到控制器。有没有办法在相邻元素上找到控制器?
答案 0 :(得分:1)
在您发表评论后,我将如何操作:使用一个对象来保存您的所有状态并将其传递给两个指令。 Demo plunker
<强> 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 :
答案 1 :(得分:0)
我一直在尝试的一种方法,因为问题是有某种控制器指令,即
<catalogue-search>
<catalogue-search-box query="{{query}}">
<catalogue-search-results></catalogue-search-results>
</catalogue-search>
然后我可以使用require语句中的parent(^)修饰符访问“controller指令”。然后,每个指令可以通过控制器指令相互通信。
这看起来是否合理还是让事情过于复杂?