使用ControllerAs和自定义指令

时间:2016-11-11 17:17:47

标签: angularjs

我似乎无法理解这里发生了什么。但是,当使用'this'关键字时,我的视图不会在按钮点击时更新;如果我使用“范围”,它会正确更新。我不确定我的自定义指令是否出错了。

//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>

2 个答案:

答案 0 :(得分:2)

您应该关注何时在javascript中使用关键字。因为这是指当前范围的上下文,当您在函数中使用 this 时,它与控制器的 this 不同。

这就是为什么你会看到控制器的所有例子都是以

开头的语法
var ctrl = this;

因此,如果您在开始时将设置为变量并将该变量用作的别名,您将获得所需的结果...

app['controller']('mainCtrl', ['$scope', function (scope) {
    var ctrl = this;

    ctrl.name ='Hello';

    ctrl.click= function(){
       ctrl.name = '';
     }
})

答案 1 :(得分:2)

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

app['controller']('mainCtrl', ['$scope', mainCtrl]);

function mainCtrl ($scope) {
    // here is your code
}

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

您也可以使用mainCtrl.yourProperty