0

我在下面创建了一个指令,它根据提供给它的数据创建一组按钮。

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
  }
});

上述指令效果很好。每次视图中的 ng-view 更改时,我都想为按钮传递一个新数组。

所以我想做以下两件事 -

  1. 注意路线的变化。

  2. 在更改路线时,更改 'btnbar.directive' 范围内的 'buttons' 变量。

我怎么做 ?

4

1 回答 1

2

您可以为其注入 $location 服务监视,然后在发生某些事情时相应地更新 $scope.buttons。这将是我的尝试

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;
        });
    }
  }
}]);

我希望这会有所帮助。

于 2012-12-15T13:16:24.280 回答