I am pretty new with Angular and I got the following problem:
I have a list view and a details view with some tags. I created a directive in order to change the route (to list view) and load new elements from a service on the click event. What I want is that the click event also change a scope variable, so that i can show/hide a button to clear filters in the list view.
Actually I am able to change the variable from the directive, but the button doesn't show/hide with ngIf/ngShow/ngHide when the variable changes.
I tried with $scope.$apply
, both in the directive and in the controller. I tried calling a toggle
function from the controller and to change the variable directly inside the directive, but nothing worked.
I tried calling the toggle function from another button and it worked perfectly!
Here is my code:
Here i try to change the variable in the directive and $apply
:
.directive('filterTag', function(getFeed, $location) {
return {
restrict: 'A',
controller: 'mainController',
link: function(scope, element, attrs) {
element.bind('click', function() {
$location.path('/list');
scope.filtered = true;
scope.$apply();
return getFeed.getTagged(this.text);
});
}
}
})
This is inside the controller:
$scope.filtered = false;
$scope.toggleFiltered = function() {
$scope.filtered = !$scope.filtered;
}
$scope.$watch('filtered', function() {
alert('filtered: ' + $scope.filtered);
});
I use $watch to be sure the variable changed correctly and it does, both from directive and from toggle button.
Here is the button i want to show/hide if filters are applied (this is in the list view):
<button type="button" ng-show="filtered">Clear filter</button>
I tried to add this button to check if I was missing something or for syntax errors, but it works perfectly
<button type="button" ng-click="toggleFiltered()">toggle filter</button>
I looked for answers in the last two days but I couldn't find the solution. Can't figure out the problem with my code.
Working example here