drivers34 drivers34 - 23 days ago 8
AngularJS Question

View is not update when using ControllerAs and custom directive

I cannot seem to understand what is going on here. When using the 'this' keyword my view does not update on the button click, however; If I use "scope" it updates correctly. I'm not sure if I did something wrong in my custom directive.

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

Answer

You should care about when you are using this keyword in javascript. Because this refer to context of current scope and when you use this in a function it is not the same with this of controller.

That is why you will see all examples of controller as syntax starts with

var ctrl = this;

So if you set this to a variable at start and use that variable as an alias of this you will get the result you want...

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

    ctrl.name ='Hello';

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