设置来自另一个控制器的angular指令的属性值

时间:2013-12-11 16:37:21

标签: angularjs angularjs-directive

Angular指令;

.directive('ngFilemanager', function () {
        return {
                    restrict: 'EA',
                    scope: {
                        thefilter: '=',
                    },
                    link: function (scope, element, attrs) {
                    },
                    templateUrl: '/templates/filemanager.html',
                    controller: FileManagerController
        }

HTML:

<div id="testcontainer" ng-controller="OtherController">
    ...
    <div ng-click="vm.myfunction">Set Filter</div> 
    ...
        <div id="thefilemanager" ng-filemanager thefilter=""></div>
    ...
</div>

如何在OtherController

的函数中设置过滤器值

我尝试通过jquery设置属性值,但是我的ng-view没有正确更新。

2 个答案:

答案 0 :(得分:5)

你有双向隔离范围,所以:

function OtherController($scope){
  $scope.myfilter= "";
  $scope.setFilter = function(what){
    $scope.myfilter = what;
  }
}

和HTML:

<div id="testcontainer" ng-controller="OtherController">
   <div ng-click="setFilter('fun')">Set Filter</div> 
   <div id="thefilemanager" ng-filemanager thefilter="myfilter"></div>
</div>

然后当您更改$scope.myfilter范围内的OtherController时,scope.thefilter会更改指令的范围。

如果“其他”控制器不是直接父级,则可以使用$ emit或$ broadcast,具体取决于目标的位置。

以下是使用$ broadcast的示例:

app.controller('MainCtrl', function($scope) {
  $scope.setFilter = function(what){
    $scope.$broadcast('setFilter', what);
  }
});

然后在你的指令里面你可以听:

link: function (scope, element, attrs) {
    scope.$on('setFilter', function(e, what){
      scope.thefilter = what;
    });
},

为了让它在任何地方都能正常工作,您可以从$ rootScope广播$,但此时您可能需要重新评估为什么必须这样做。 Angular本身做了很多,例如,routeChangeSuccess事件,但这并不意味着你应该这样做。

答案 1 :(得分:0)

如果其他控制器是ngFilemanager

的父级,则此方法有效
<div id="thefilemanager" ng-filemanager thefilter="theFilterValue"></div>

在其他一些控制器中

...
$scope.theFilterValue = 'some other value';
...

查看文档的isolate scope on directives部分

相关问题