当使用controllera和custom指令时,视图不会更新



我似乎不明白这里发生了什么。当使用"this"关键字时,我的视图不更新按钮点击,但是;如果我使用"scope",它就会正确更新。我不确定我是否在自定义指令中做错了什么。

//My custom directive
app['directive']('myCustomDirective',function(){
return{
   restrict: 'E',
   templateUrl: 'templates/someTemplate.html',
   controller: 'mainCtrl',
   controllerAs: 'ctrl'
}

})

//My controller, will not update view on click
app['controller']('mainCtrl', ['$scope', function (scope) {
    this['name'] ='Hello';
    this['click'] = function(){
       this['name'] = '';
     }
})
//Portion of HTML from view.
<input type="text" ng-model="ctrl.name" required/>
<md-button class="md-primary" ng-click="ctrl.click()">Submit</md-button>

//However; if I use the scope (like below) it will update the view
app['controller']('mainCtrl', ['$scope', function (scope) {
   scope['name'] ='';
   this['click'] = function(){
   scope['name'] = "You entered your name";
   }
})
//Will update the update the view on button click.
<input type="text" ng-model="name" required/>
<md-button class="md-primary" ng-click="ctrl.click()">Submit</md-button>

你应该注意在javascript中何时使用这个关键字。因为这是指当前作用域的上下文,当你在函数中使用this时,它与控制器的this不一样。

这就是为什么你会看到所有controller as语法的例子都以

开头的原因
var ctrl = this;

如果你在开始时设置this为一个变量并使用该变量作为this的别名你将得到你想要的结果…

app['controller']('mainCtrl', ['$scope', function (scope) {
    var ctrl = this;
    ctrl.name ='Hello';
    ctrl.click= function(){
       ctrl.name = '';
     }
})

如果您想使用this而不是$scope,您必须这样编写控制器:

app['controller']('mainCtrl', ['$scope', mainCtrl]);
function mainCtrl ($scope) {
    // here is your code
}

如果控制器内部的代码比较复杂,最好的做法是定义var that = this;并在子级别使用that而不是this

也可以使用mainCtrl.yourProperty

最新更新