2016-03-22 32 views
1

我試圖創建一個指令,調用父控制器上定義的方法。Angular 1.x指令共享作用域與控制器的父親

I've made a plnkr here

我使用控制器作爲父控制器的虛擬機「。該方法不在指令tho上調用。我如何從指令調用父控制器上的方法?

(function() { 
    var myApp = angular.module('myApp', []); 

    myApp.controller('MyCtrl', MyCtrl); 

    MyCtrl.$inject = []; 

    function MyCtrl() { 
    this.title = 'Test'; 

    this.sayHello =() => { 
     this.output = 'Hello'; 
    } 

    } 

    myApp.directive('sayHello', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     template: '<a href="#" ng-click="vm.sayHello();">Click to say hello</a>' 
    } 
    }) 
})(); 
+0

我測試你的plunkr,這確實調用父功能。 – Aliz

+0

你是說你得到了你好的輸出嗎?因爲我不是 – AlxVallejo

+0

當然沒有輸出,你可以將「output」的值改爲「Hello」,使用「console.log」或「alert()」,你會看到你的函數被調用,請參閱:https://plnkr.co/edit/3S5bglFxi0ifsx6uyMJT?p = preview – Aliz

回答

1

我已經改變了代碼,而現在它的工作:

<!DOCTYPE html> 
<html> 
    <head> 
    <script data-require="[email protected]" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script> 
    <link rel="stylesheet" href="style.css" /> 
    <script src="script.js"></script> 
    </head> 

    <body> 
    <div ng-app="myApp"> 
     <div ng-controller="MyCtrl as vm"> 
     <h3>{{vm.title}}</h3> 
     <say-hello></say-hello> 

     <h4>{{vm.output}}</h4> 
     </div> 
    </div> 
    </body> 

</html> 
相關問題