[英]Data binding in directive controller
I have a collection of buttons that sort a list of items when clicked: 我有一组按钮,这些按钮在单击时对项目列表进行排序:
<div ng-controller="MainCtrl">
<sort-buttons target="filters.sort">
<sort-button></sort-button>
<sort-button></sort-button>
<sort-button></sort-button>
</sort-buttons>
</div>
I want the parent directive to save the results of the buttons to the $scope.filters.sort
property on the MainCtrl
controller via the target
attribute, but how can I actually save to where the target
attribute points to? 我希望父指令通过
target
属性将按钮的结果保存到MainCtrl
控制器上的$scope.filters.sort
属性中,但是如何才能实际保存到target
属性指向的位置?
Here's what I have: 这是我所拥有的:
app.directive('sortButtons', [function(){
return {
restrict: 'E',
controller: function($scope, $element, $attrs) {
// this.foo() should save to target
this.foo = function(){
console.log('click');
};
}
}
}]).directive('sortButton', ['Config', function(Config) {
var basePath = Config.get().paths.base;
return {
restrict: 'AE',
replace: true,
require: '^sortButtons',
scope: {
label: '@',
orderBy: '&'
},
templateUrl: basePath + 'js/fantasy/templates/sort-button.htm',
link: function(scope, elem, attrs, ctrl) {
elem.on('click', function(){
ctrl.foo();
});
}
}
}]);
Try $eval
on attr.target
like 在
attr.target
上尝试$eval
var data = $scope.$eval($attrs.target)
Or if your data is dynamic you can $watch the attr 或者,如果您的数据是动态的,则可以$ attr
var data = [];
$scope.$watch($attrs.target, function(newValue, oldValue){
data = newValue;
})
Also correct your controller injection like below, else if you will get error if you minified your source code. 还要像下面那样更正控制器注入,否则如果缩小源代码会出现错误。
controller: ['$scope','$element','$attrs', function($scope, $element, $attrs) {
var data = $scope.$eval($attrs.target)
this.foo = function(){
console.log('click');
};
}]
What I went with was removing the target
attribute altogether, and instead broadcasting on the $rootScope
. 我所要做的就是完全删除
target
属性,而是在$rootScope
上广播。
Directive: 指示:
this.foo = function(){
$rootScope.$broadcast('sortButtons', {
predicate: 'foo',
reverse: false
});
};
Controller: 控制器:
$rootScope.$on('sortButtons', function(event, data){
$scope.filters.sort = data;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.