无法将功能传递给指令

时间:2015-09-21 17:43:08

标签: angularjs angularjs-directive angularjs-controller

我有一个控制器和指令定义为:

angular.module('cms', ['TestMod'])
.controller('MainCtrl', function() {
  this.refreshPage = function() {
    alert('Hello World');
  };
});

angular.module('TestMod', [])
.directive('testCtl', function() {
  return {
    scope: {
      tmOnClose: '&',
    },
    template: '<div ng-click="close()">Hello World</div>',
    link: function(scope, element, attrs) {
      scope.close = function() {
        if(scope.tmOnClose)
            scope.tmOnClose();
      }
    }
  }
 })

在我的HTML中,我试图将refreshPage函数传递给指令,如:

<html ng-app="cms">

    <head>
        <script data-require="angular.js@1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js"></script>
    </head>

    <body ng-controller="MainCtrl">
        <h1>Hello Plunker!</h1>
        <test-ctl tm-on-close="refreshPage"></test-ctl>
    </body>
</html>

当我单击该指令时,将调用close函数,但从不调用refreshPage函数。调试时,scope.tmOnClose()的值始终为

function(b)(return n(a,b))

如何获取实际功能,以便我可以在指令中调用它?

Plunker Here

编辑:我必须告诉自己。我从一个更大的项目中设置了这个样本,因为我不想在这里找不到相关的代码页面。塞尔吉奥的回答是100%正确的,实际上是我遇到的问题。然而,我更大的问题是,在我的大型应用程序中,我没有包含在我定义的控制器中。我把它作为一个注释添加到希望帮助其他人,因为在这样的情况下,显然有角度的,不会告诉你某些东西是未定义的,它只是定义它并传递它。

3 个答案:

答案 0 :(得分:2)

首先,给控制器命名。其次,在带有&隔离范围的指令中使用时调用该函数。

<body ng-controller="MainCtrl as ctrl">
    <h1>Hello Plunker!</h1>
    <test-ctl tm-on-close="ctrl.refreshPage()"></test-ctl>
</body>

答案 1 :(得分:0)

使用&amp;你必须像这样引用它:

<test-ctl tm-on-close="refreshPage()"></test-ctl>

答案 2 :(得分:-1)

函数可以通过&#39; =&#39;传递给指令在范围对象

angular.module('cms', ['TestMod'])
 .controller('MainCtrl', function() {
      this.refreshPage = function() {
      alert('Hello World');
  };
 });

angular.module('TestMod', [])
 .directive('testCtl', function() {
     return {
       scope: {
         tmOnClose: '=',
       },
       template: '<div ng-click="close()">Hello World</div>',
       link: function(scope, element, attrs) {
              scope.close = function() {
              if(scope.tmOnClose)
                scope.tmOnClose();
          }
        }
       }
  })

&#34;控制器为&#34;必须使用语法,因为控制器范围是使用refreshPage函数

声明的
<!DOCTYPE html>
<html ng-app="cms">

  <head>
    <script data-require="angular.js@1.4.6" data-semver="1.4.6"   src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="MainCtrl as ctrl">
    <h1>Hello Plunker!</h1>
    <test-ctl tm-on-close="ctrl.refreshPage"></test-ctl>
  </body>

</html>
相关问题