0

My value, stored in data, gets displayed on the viewer when I assign to $scope and refer to it in the viewer as {{data}} but not when I assign it to a field inside my controller and refer to it as {{controller.thing.data}}. In the latter scenario, I see no errors in the console and I see thing.data getting populated when I set a breakpoint.

Where am I going wrong ?

Viewer

<html ng-app="controller" ng-controller="MyController as controller">
<head>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.min.js"></script>
  <script type="text/javascript" src="controller.js"></script>
  <script type="text/javascript" src="services.js"></script>
</head>
<body>
  {{controller.thing.data}}
</body>
</html>

Controller

angular.module('controller', ['services'])
.controller('MyController', ['MyService', '$scope', function(MyService, $scope) {
  var thing = this;
  MyService.getData().then(function(data) {
    thing.data=data;
  });
}]);
AfterWorkGuinness
  • 1,780
  • 4
  • 28
  • 47
  • 1
    Typo. Just do `controller.data`, the thing `thing` is controller instance itself. – PSL Jun 10 '15 at 17:38
  • Thanks. That did the trick. Can you tell me why it works like that, but if I do this.data=data; and then {{controller.data}} in the viewer it doesn't work ? Is it because the this is not referencing the controller in that scope ? – AfterWorkGuinness Jun 10 '15 at 17:42
  • [This will answer question about `this`](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) and `thing` is just a variable reference to `this` and it is not a property on the controller instance.. so controller.thing does not exist. instead you are just setting data on controller itself – PSL Jun 10 '15 at 17:44

0 Answers0