I have created a directive below, which creates a set of buttons based on the data that is provided to it.
angular.module('btnbar.directive', ['messaging']).
directive("btnBar", function(){
return {
restrict: 'E',
$scope.buttons = [{href: '#/students', icon:'icon-ok'},
{href: '#/students', icon:'icon-remove'},
{href: '#/students/new', icon:'icon-plus'}];
},
template:'<div class="btn-toolbar">' +
'<a class="btn" ng-repeat="b in buttons" href={{b.href}}>' +
'<i class={{b.icon}}></i></a></div>',
replace:true
}
});
The above directive works well. Every time the ng-view in the view changes, I would like to pass a new array for the buttons.
So I want to do the following 2 things -
Watch for the change in the route.
On change in the route, change the 'buttons' var in the 'btnbar.directive' scope.
How do I do that ?
You can inject the $location service watch for it and then update the $scope.buttons accordingly when something happens. This would be my attempt
angular.module('btnbar.directive', ['messaging']).
directive("btnBar", ['$location', function($location){
return {
restrict: 'E',
template:'<div class="btn-toolbar">' +
'<a class="btn" ng-repeat="b in buttons" href={{b.href}}>' +
'<i class={{b.icon}}></i></a></div>',
replace:true,
link: function($scope, $element, $attrs) {
$scope.buttons = [{href: '#/students', icon:'icon-ok'},
{href: '#/students', icon:'icon-remove'},
{href: '#/students/new', icon:'icon-plus'}];
// What for the location
$scope.$watch(function() {
// You can define what part of the $location you want to watch for
// E.g. $location.search().something (if you are only interested in that)
return $location;
}, function(newValue, oldValue) {
// Do something with the $scope.buttons;
});
}
}
}]);
I hope that helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.