[英]Angular service/value is not picking up new var from $(document).ready()
I have an Angular service/value that is attempting to pick up a variable, but it picks up the original instead of the new one. 我有一个Angular服务/值,它试图获取一个变量,但是它获取的是原始变量而不是新变量。 The new variable should be the one inside $(document).ready() as seen below: 新变量应该是$(document).ready()中的变量,如下所示:
var app = angular.module("app", []);
var db = "asdf"
$(document).ready(function(){
// document.getElementById("DB_content").value === '[{"name":"Joe", "age":"19"}, {"name":"Jill", "age":"21"}]'
db = document.getElementById("DB_content").value;
console.log(db);
});
app.value("DBcontent", db);
But instead of DBcontent holding the string "array", it is holding "asdf". 但是,不是DBcontent持有字符串“ array”,而是持有“ asdf”。 I suspect it is because app.value("DBcontent", db) is being executed immediately, even before $(document).ready(). 我怀疑这是因为app.value(“ DBcontent”,db)甚至在$(document).ready()之前都会立即执行。 I have tried putting var db outside of $(document).ready() but that breaks it. 我尝试将var db放在$(document).ready()之外,但这会破坏它。 Does anyone know what I can do here? 有人知道我在这里可以做什么吗?
https://jsfiddle.net/dop49d54/4/ https://jsfiddle.net/dop49d54/4/
app.value(...)
runs immediately, before $(document).ready(...)
app.value(...)
在$(document).ready(...)
之前立即运行
If you want it to have the value acquired in $(document).ready(...)
you need to move it inside that event handler. 如果要在$(document).ready(...)
获取值,则需要将其移到该事件处理程序中。
$(document).ready(function(){
var app = angular.module("app", []);
// document.getElementById("DB_content").value === '[{"name":"Joe", "age":"19"}, {"name":"Jill", "age":"21"}]'
var db = document.getElementById("DB_content").value;
console.log(db);
app.value("DBcontent", db);
});
Moving the <script>
tag down to the bottom of the <body>
will work! 将<script>
标记向下移动到<body>
的底部将起作用!
<script>
var db = "asdf";
(function go(){
db = document.getElementById("DB_content").value;
console.log(db);
app.value("DBcontent", db);
})();
<script>
Fundamentally you have marked the db
variable inside the $document.ready()
function as local by prefixing it with var
. 从根本上讲,您已经在$document.ready()
函数内将db
变量标记为local,方法是在变量前加上var
前缀。
The db
variable inside the function wouldn't update your global db
variable defined next to the angular app. 函数内部的db
变量不会更新您在angular应用程序旁边定义的全局db
变量。
Also note that app.value("DBcontent", db);
还要注意app.value("DBcontent", db);
runs before the $document.ready()
. 在$document.ready()
之前运行。 If you need to feed an angular variable with something from the DOM, make the DOM element a directive and set the values in the scope. 如果您需要使用DOM中的内容来提供角度变量,则将DOM元素设为指令并在范围中设置值。 Or you can also use ng-init
in this case. 或者您也可以在这种情况下使用ng-init
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.