【问题标题】:calling a controller function from a link in a directive从指令中的链接调用控制器函数
【发布时间】:2016-03-14 21:11:50
【问题描述】:

我正在编写一个 Angular 1.5.0-beta2 项目。

我想从返回对象的链接属性中调用一个控制器函数。

意思是……

angular.module('myalcoholist').directive("ngFileSelect",function() {

    return {
        controller: 'AddCoctailController',
        controllerAs: 'addCocktail',
        link: function ($scope, el) {

            el.bind("change", function (e) {

                var file = (e.srcElement || e.target).files[0];
/*THIS DOES NOT WORK */      addCocktail.getFile(file);
            })

        }

    }
});

正如您在此处看到的,我正在尝试运行一个名为 getFile 的控制器函数。

有可能吗?

【问题讨论】:

  • $scope.addCocktail - 你试过了吗?
  • 是的。我将功能添加到控制器,而不是范围

标签: angularjs angular-directive


【解决方案1】:

控制器用于填充 $scope 并且链接在控制器之后运行,因此您可以在链接函数中访问范围内的任何内容。

angular.module('app', [])
  .directive('tstDrv', function () {
      return {
          restrict: 'E',
          template: '<div>{{hello}}</div>',
          link: function (scope) {
              console.log(scope.hello);
              scope.hello = "hello again";
          },
          controller: function ($scope) {
              $scope.hello = 'tst';
          }
      }
  })

这个SO问题也与Angular: calling controller function inside a directive link function using &有关

如果想要访问在当前指令范围之外定义的范围属性,这一切都取决于“域定义对象”的范围属性。

参考。 https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance

【讨论】:

  • 有没有办法在不使用 $scope 的情况下从控制器运行功能?
  • 感谢您的输入,但这并不能完全回答我的问题。也许这是不可能的,但我想知道我是否可以从父控制器调用一个函数或在父控制器中设置一个变量
  • 您没有提到您想从该指令中获得对 $parent 的保留。让我更新我的答案。
【解决方案2】:

添加到上面 Chris 的答案 - 链接有几个参数(范围、元素、属性、控制器)。您可以通过以下方式访问附加的控制器功能:

link: function(scope, elem, attrs, ctrl){
    ctrl.func_to_call();
}

【讨论】:

    【解决方案3】:

    如果您使用角度 >= 1.3,请使用 bindToController 选项

    angular.module('myalcoholist').directive("ngFileSelect",function() {
    
        return {
            controller: 'AddCoctailController',
            controllerAs: 'addCocktail',
            bindToController: true,
            link: function (scope, el) {
    
                el.bind("change", function (e) {
    
                    var file = (e.srcElement || e.target).files[0];
                    scope.addCocktail.getFile(file);
                });
    
            }
    
        }
    });
    

    codepen:http://codepen.io/gpincheiraa/pen/VeYxGN

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-28
      • 2015-03-01
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 1970-01-01
      相关资源
      最近更新 更多