javascript 如何使用 AngularJS 在 ng-init 中传递范围变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28770156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass scope variable in ng-init using AngularJS
提问by Lulzim
I have problem passing the variable declared from the scope to ng-init:
我在将范围内声明的变量传递给 ng-init 时遇到问题:
so far I have something like this:
到目前为止,我有这样的事情:
$scope.x = '10';
<div ng-controller = "controller" ng-init="function(x)">
How do I pass x var from the scope inside ng-init function?
如何从 ng-init 函数内的作用域传递 x var?
回答by Mike Robinson
A lot of people will tell you you shouldn't do this (as mentioned in the docs here: https://docs.angularjs.org/api/ng/directive/ngInit).
很多人会告诉您不应该这样做(如此处的文档中所述:https: //docs.angularjs.org/api/ng/directive/ngInit)。
As for actually doing it....
至于实际做....
<div ng-controller="controller" ng-init="x = x">
回答by Kieran
If you wanted to push a value in using the ng-init i would use something like this
如果你想在使用 ng-init 时推送一个值,我会使用这样的东西
Js code
js代码
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.x = "this will be replaced"; //not really needed
$scope.initialize = function(bar){
$scope.x=bar;
}
})
and html
和 html
<div ng-app="app" ng-controller="ctrl" ng-init="initialize('your value')">
回答by Lee Lee
Maybe this one can help you:
也许这个可以帮助你:
$scope.x = '10';
<div ng-controller = "controller" ng-init="x">
回答by jlowcs
If you want to execute a function on a tag where you have a controller, why not simply run the function in the controller's constructor (i.e. function)?
如果要在具有控制器的标签上执行函数,为什么不简单地在控制器的构造函数(即函数)中运行该函数?
Not everything has to be in the markup.
并非所有内容都必须在标记中。
JS:
JS:
angular.module(...).controller('MyController', function ($scope) {
$scope.myFunction($scope.x);
})
HTML:
HTML:
<div ng-controller="MyController"></div>