4

In index.html, I am doing something like this:

<div ng-controller="MyController">
    <div ng-model="pk" ng-init="pk='2'"></div>
</div>

Anyway, in my angular file, I am doing something like this:

.controller('MyController', [
  '$scope', function($scope) {
    alert('Sup ' + $scope.pk);
  }
])

So lets say the pk for a URL is 2, I expect to see something like this:

Sup 2

However, my output is this :

Sup undefined

What am I doing wrong? Thanks!

darkhorse
  • 8,192
  • 21
  • 72
  • 148

4 Answers4

2

This happens, because code from controller execute before code from view, so when run

alert('Sup ' + $scope.pk);

ng-init - not execute.

So, for solution, you can simple assign value inside controller, or use solution from other answers like watch, or timeout

Grundy
  • 13,356
  • 3
  • 35
  • 55
1

Delay the alert with $timeout:

.controller('myCtrl', [
  '$scope', '$timeout', function($scope, $timeout) {
    $timeout(function() 
      alert('Sup ' + $scope.pk);
    });
  }
]);
Lukasz Wiktor
  • 19,644
  • 5
  • 69
  • 82
1

Use $scope.$watch:

.controller('MyController', ['$scope', function($scope) {
    $scope.$watch('pk', function(newValue, oldValue) {
        alert('Sup ' + newValue);
    });
}]);

Your alert('Sup ' + $scope.pk); is called before the view has been initialized and therefore before ng-init is called.

martin
  • 93,354
  • 25
  • 191
  • 226
1

Angular has a trick that should always be followed: "Always use a dot in models". For example:

ng-model="models.pk"

See more in this answer.

You should also consider following some guidelines from John Papa that prevent that kind of problems, see here one example. Try it and tell me how it went.

Community
  • 1
  • 1
Pedro Silva
  • 263
  • 2
  • 17