简体   繁体   中英

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!

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

Delay the alert with $timeout :

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM