2

I am trying to update the model and view using data fetched from ajax.

using $scope (this works):

<div ng-controller="myCtrl">
    <ul>
        <li ng-repeat="a in arr">{{a}}</li>
    </ul>
</div>

 var app = angular.module("app", [])
 app.controller("myCtrl", function($scope,$http)
 {
     $scope.arr = [];
     $http.get("/angular/ajax").success(function(data){
         $scope.arr = JSON.parse(data);
     });
 });

but when I try with 'controller as' it doesn't

<div ng-controller="myCtrl as mc">
    <ul>
        <li ng-repeat="a in mc.arr">{{a}}</li>
    </ul>
</div>

var app = angular.module("app", [])
app.controller("myCtrl", function ($scope,$http) {
    this.arr = [];
    $http.get("/angular/ajax").success(function(data){
        this.arr = JSON.parse(data);
    });
});

P.S. beginner in angularjs.

6119
  • 99
  • 8

1 Answers1

1

this is going not going to refer to the correct scope inside of your success function. In order to get it working you need to store this inside of a variable so you can use it inside of other functions.

var vm = this;  // view model
vm.arr = [];
...
vm.arr = JSON.parse(data);

And you would use the same template logic.

csbarnes
  • 1,873
  • 2
  • 28
  • 35
  • thanks for the answer, double thanks for quick reply.....SO is making me wait for 8 mins before I select your answer... – 6119 Dec 07 '15 at 19:57
  • No worries. `this` has some weird properties and isn't very intuitive. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this explains the details pretty well. – csbarnes Dec 07 '15 at 20:02