darkhorse
darkhorse

Reputation: 8722

How to inject a variable from scope into an Angular controller?

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!

Upvotes: 4

Views: 243

Answers (4)

Pedro Silva
Pedro Silva

Reputation: 263

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.

Upvotes: 1

martin
martin

Reputation: 96889

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.

Upvotes: 1

Lukasz Wiktor
Lukasz Wiktor

Reputation: 20422

Delay the alert with $timeout:

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

Upvotes: 1

Grundy
Grundy

Reputation: 13381

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

Upvotes: 2

Related Questions