我有这样一个过滤器指令:
app.directive('filter', function(){
return {
restrict: 'E',
transclude: true,
scope: {
callFunc: '&'
},
template:
' <div>' +
' <div ng-transclude></div>' +
' </div>',
controller: function($scope, $element, $attrs){
this.getData = function() {
$scope.callFunc()
}
}
}
});
app.directive('positions', function(){
return {
require: '^filter',
scope: {
selectedPos: '='
},
template:
' Positions: {{selectedPos}}' +
' <ul>' +
' <li ng-repeat="pos in positions">' +
' <a href="#" ng-click="setPosition(pos); posRegData()">{{pos.name}}</a></a>' +
' </li>' +
' </ul>',
controller: function($scope, $element, $attrs){
$scope.positions = [
{name: '1'},
{name: '2'},
{name: '3'},
{name: '4'},
{name: '5'}
];
$scope.selectedPos = $scope.positions[0].name;
$scope.setPosition = function(pos){
$scope.selectedPos = pos.name;
};
},
link: function(scope, element, attrs, filterCtrl) {
scope.posRegData = function() {
filterCtrl.getData();
}
}
}
})
还有控制器:
app.controller('keyCtrl', ['$scope', function($scope) {
var key = this;
key.callFunc = function() {
key.value = key.selectedPos;
console.log(key.selectedPos)
}
}]);
主要问题是为什么控制器中的
key.selectedPos
只有在第二次点击时才获取正确的值?这里有一个Plunker示例复制我的问题。
一种解决方法是在调用
callFunc()
时发送一个参数。然后,我在控制器中更新函数:key.callFunc = function(filterParams)
,同时,我也更新了传递的方法call-func="key.callFunc(filterParams)
。然后,在
filter指令
中,我将getData方法更改为:this.getData = function(val) {
$scope.callFunc({filterParams: val})
}
在
positions directive
中,我传递需要的值:scope.posRegData = function() {
filterCtrl.getData({position: scope.selectedPos});
}
最后,在
keyCtrl
中,我是这样获取值的:key.callFunc = function(filterParams) {
key.value = filterParams.position;
console.log(filterPrams.position)
}
这是一个展示这种尝试的plunker。
在这种情况下,问题是这是否是一种好的做法,要记住它是在一个非常大的应用程序中。