简体   繁体   English

如何将范围中的变量注入Angular控制器?

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

In index.html , I am doing something like this: index.html中 ,我做的是这样的:

<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: 那么让我们说URL的pk为2,我希望看到这样的东西:

Sup 2 Sup 2

However, my output is this : 但是,我的输出是这样的:

Sup undefined 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. ng-init - 不执行。

So, for solution, you can simple assign value inside controller, or use solution from other answers like watch , or timeout 因此,对于解决方案,您可以在控制器内部简单地分配值,或者使用其他答案(如watchtimeout解决方案

Delay the alert with $timeout : 使用$ timeout延迟警报:

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

Use $scope.$watch : 使用$scope.$watch

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

Your alert('Sup ' + $scope.pk); 你的alert('Sup ' + $scope.pk); is called before the view has been initialized and therefore before ng-init is called. 在视图初始化之前调用,因此在调用ng-init之前调用。

Angular has a trick that should always be followed: "Always use a dot in models". Angular有一个应该始终遵循的技巧:“始终在模型中使用点”。 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. 您还应该考虑遵循John Papa的一些指导来防止这类问题,请参阅此处的一个示例。 Try it and tell me how it went. 试试吧,告诉我它是怎么回事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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