2014-06-19 41 views
0

我知道這一定是我忽略的一件簡單的事情,但谷歌現在不是我的朋友。templateUrl上的Angular.js「Controller As」/ template ng-click/blur/focus events does not working?

當使用"controllerAs"語法,出於某種原因,如果我用它爲元素的模板內,點擊次數不登記。 這裏有一個plunkr

HTML

<section ng-controller="MainCtrl as main"> 
    <p>Hello {{main.name}}!</p> 
    <div class='button' ng-click="main.openDoor()">You can click this and it will alert!</div> 

    <dude class='button'></dude> 
</section> 

JS

var app = angular.module('plunker', []); 

app.directive('dude', function(){ 
    return { 
    restrict: "E" 
    , scope: {} 
    , controller : 'main' 
    , controllerAs: 'main' 

// vv confusion 

    , template: '<div ng-click="main.openDoor()">This is a different thing but clicking it does nothing even though i literall copy pasted this element!</div>' 

// ^^confusion 

    , transclude : true 
    } 
}).controller("MainCtrl", function(){ 
    this.name = "true"; 
    this.openDoor = function(){  // <==== confusion. 
    alert(Object.keys(this)); 
    }; 
}); 

回答

3

你沒有正確設置指令的控制器,它應該是:

controller : 'MainCtrl'

而非maincontroller屬性分配實際控制器,而controllerAs給控制器對象提供別名,控制器對象在控制器中使用this進行編輯。

Docs reference

更新plunker