在Angular js中,在指令中调用模块控制器的方法,默认情况下不会看到它的作用域

Angular js, call module controller's method in the directive, which doesn't see it's scope by default

本文关键字:作用域 情况下 默认 调用 指令 模块 控制器 方法 Angular js      更新时间:2023-09-26

问题是:我在应用程序配置中指定了路由,如:

when('/url', {
    controller: 'Controller',
    templateUrl: 'url'
  });

在视图中我只有:

<div ng-view my-directive="fire()"></div>

重要的是没有'ng-controller="MyController"'属性。当用户加载url时,控制器触发,模板被模型数据填充并渲染好。

然后我有一个指令,必须在同一页面上执行以下操作:当我单击时,"控制器"必须执行函数,获取数据并添加渲染模板/添加数据到现有。

指令是:

myAppModule.directive('myDirective', function() {
  return {
    restrict: 'A',
    templateUrl: 'url',
    replace: false,
    link: function(scope, element, attrs) {
        var raw = element[0];
        element.bind('click', function() {
                console.log('loaddata');
                scope.$apply(attrs.fire);
        });
      }
  };
});

console.log正在触发,但是scope.$apply(attrs.fire) -"Controller"内部的fire()函数没有。关键提示有:如果我在html中添加ng-controller="Controller",它会工作,但会在页面加载时触发两次。那么如何告诉指令执行"控制器"火灾方法不使用ng-controller="控制器"?

您可以使用scope.$eval(),它将调用该方法。

link: function(scope, element, attrs) {
    var raw = element[0];
    var func = attrs.myDirective;   // gets the value fire()
    element.bind('click', function() {
            console.log('loaddata');
            scope.$eval(func);
            // you shouldn't need to call $apply here
            // since func will be executed within the 
            // controller
    });
}