从另一个角度控制指令的设置属性值 [英] Set attribute value of angular directive from another controller

查看:88
本文介绍了从另一个角度控制指令的设置属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

角指令;

.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>

如何设定thefilter值 OtherController

How can i set thefilter value in a function of OtherController?

我试图通过jquery的设置属性值,但没有更新我的NG-观点正确即可。

I tried setting the attribute value by jquery but my ng-view isn't updated correctly then.

推荐答案

您已经有了双向隔离范围,以便:

You've got bi-directional isolated scope so:

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 在指令的范围发生变化。

Then when you change $scope.myfilter in the OtherController's scope, scope.thefilter changes in your directive's scope.

如果其他控制器不是直接的父母,你可以使用$发射或$播出不同的地方的目标。

If the "other" controller is not a direct parent, you could use $emit or $broadcast depending on where the target is.

下面是一个使用$来代替广播一个例子:

Here's an example using $broadcast instead:

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

那么你的指令,在里面可以听:

then inside your directive you can listen:

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

要使它在任何地方工作,你可以从$ $ rootScope播出,但在这一点上你为什么要做到这一点,你可能要重新评估。角本身是这个有很多,例如,routeChangeSuccess事件,但是,这并不意味着你应该这样做。

To make it work anywhere, you can $broadcast from $rootScope, but at that point you might want to re-evaluate why you have to do this. Angular itself does this a lot, for example, routeChangeSuccess event, but that doesn't mean you should do it.

这篇关于从另一个角度控制指令的设置属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆