2014-06-19 45 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