angularjs - this reference in callback with controllerAs-Syntax -


i'm working on angularjs project , i'm trying implement close possible angularjs 2.

in angularjs 2 there no more ng-controller , $scope, i'm using directives instead of ng-controller. i'm trying avoid use of $scope using controlleras-syntax.

my directives this:

angular.module('myapp').directive('mydirective', function() {     return {         controller: function() {             this.data = '123';         },         controlleras: 'ctrl',         template: ' <p>{{ctrl.data}}</p> '     }; }); 

so far works fine. problems start when i'm trying call methode or property on controller within callback-function. in case 'this' not referencing actual controller-instance more.

example:

angular.module('myapp').directive('mydirective', function($http) {     return {         controller: function() {             this.data = '';              this.loaddata = function(){                 $http.get("someurl.com")                 .success(function(response) {                     this.data = response.data; // --> doesn't work                  });             }              this.loaddata();         },         controlleras: 'ctrl',         template: ' <p>{{ctrl.data}}</p> '     }; }); 

is there way reference controller-instance within callback can use controllers methods , properties within callback?

what need store reference this in variable @ beginning of controller...then add properties variable. context won't lost inside callbacks way.

a common convention use var vm "view model" naming of variable subjective

angular.module('myapp').directive('mydirective', function($http) {     return {         controller: function() {             var vm = this;              vm.data = '';              vm.loaddata = function(){                 $http.get("someurl.com")                 .success(function(response) {                     vm.data = response.data;                   });             }              vm.loaddata();         },         controlleras: 'ctrl',         template: ' <p>{{ctrl.data}}</p> '     }; }); 

a popular angular style guide


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -