2015-09-21 136 views
0

我有一個控制器和指令定義爲:不能通過功能指令

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="[email protected]" 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%正確的,實際上是我遇到的問題。但是,我的更大的問題是,在我的更大的應用程序中,我沒有被包含在我的控制器中。我添加這個作爲一個註釋,希望可以幫助別人,因爲在這種情況下,顯然angularjs不會告訴你某些東西是未定義的,它只會定義它並將其傳入。

回答

2

首先,給一個名字給你的控制器。其次,在使用&隔離範圍的指令中調用函數。

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

當使用&你必須引用它是這樣的:

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

函數可以在範圍對象被傳遞到一個指令與 '='

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(); 
      } 
     } 
     } 
    }) 

「控制器」必須使用語法,因爲控制器範圍是使用refreshPage函數聲明的

<!DOCTYPE html> 
<html ng-app="cms"> 

    <head> 
    <script data-require="[email protected]" 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>