Recently, I've been working on a custom filter directive in Angular:
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();
}
}
}
})
Here's the controller code snippet related to the directive:
app.controller('keyCtrl', ['$scope', function($scope) {
var key = this;
key.callFunc = function() {
key.value = key.selectedPos;
console.log(key.selectedPos)
}
}]);
I noticed that the value for key.selectedPos
in the controller is only updated correctly on the second click. Any insights into why this might be happening?
You can view a live example of this issue on Plunker.
One possible workaround involves passing a parameter when calling the callFunc()
method.
In this approach, I update the function in the controller:
key.callFunc = function(filterParams)
, and modify the usage of the method as call-func="key.callFunc(filterParams)
Then, within the filter
directive, I adjust the getData method like so:
this.getData = function(val) {
$scope.callFunc({filterParams: val})
}
In the positions
directive, I pass the relevant value like this:
scope.posRegData = function() {
filterCtrl.getData({position: scope.selectedPos});
}
Finally, in keyCtrl
, I access the value as follows:
key.callFunc = function(filterParams) {
key.value = filterParams.position;
console.log(filterPrams.position)
}
For a practical demonstration of this alternate approach, check out this Plunker.
Considering the scale of your application, do you think this method is a viable solution?