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

dan*_*iel 4 angularjs angularjs-directive

角度指令;

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

HTML:

<div id="testcontainer" ng-controller="OtherController">
    ...
    <div ng-click="vm.myfunction">Set Filter</div> 
    ...
        <div id="thefilemanager" ng-filemanager thefilter=""></div>
    ...
</div>
Run Code Online (Sandbox Code Playgroud)

如何在函数中设置过滤器值OtherController

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

Jon*_*wny 5

你有双向隔离范围所以:

function OtherController($scope){
  $scope.myfilter= "";
  $scope.setFilter = function(what){
    $scope.myfilter = what;
  }
}
Run Code Online (Sandbox Code Playgroud)

和HTML:

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

然后,当你改变$scope.myfilterOtherController的范围内,scope.thefilter在你的指导的范围内变化.

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

以下是使用$ broadcast的示例:

app.controller('MainCtrl', function($scope) {
  $scope.setFilter = function(what){
    $scope.$broadcast('setFilter', what);
  }
});
Run Code Online (Sandbox Code Playgroud)

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

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

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