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!

6
  • Does it work if you manually write ng-init="pk='2'"? Commented Mar 2, 2016 at 9:02
  • Nope. That doesn't work either :/ Commented Mar 2, 2016 at 9:10
  • 1
    So your problem has nothing to do with Django. Commented Mar 2, 2016 at 9:11
  • I think you shoud use ng-value not ng-init Commented Mar 2, 2016 at 9:15
  • ng-value does not work either. Oh and I updated the question to make it more simpler and easier to answer. Commented Mar 2, 2016 at 9:31

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

1

Delay the alert with $timeout:

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

Comments

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.