在templateUrl / template ng-click / blur / focus事件不起作用的Angular.js“Controller As”?

时间:2014-06-19 19:39:13

标签: javascript angularjs syntax angularjs-controller

我知道这必须是一件我能忽视的简单事情,但谷歌现在不是我的朋友。

使用"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));
  };
});

1 个答案:

答案 0 :(得分:3)

您没有正确设置指令的控制器,它应该是:

controller : 'MainCtrl'

而不是maincontroller属性指定实际控制器,而controllerAs为控制器对象提供别名,该控制对象在控制器中使用this进行编辑。

Docs reference

更新了plunker

相关问题