[英]Angular JS $http.get() $scope Issue
我試圖完成似乎應該是一個簡單的任務,但是我很沮喪。
這是我能想到的最簡單的例子。
<html lang="en" data-ng-app="myApp">
<head>
<script src="js/angular.js"></script>
<script>
var test = 'Hello World';
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function ($scope) {
$scope.testStr = test;
});
myApp.run(function($http){
test = 'scope updates';
$http.get("controllers/getTestStr.jsp").success(function (data) {
//console.log('returned');
test = 'scope does not update';
});
});
</script>
</head>
<body ng-controller="myCtrl" style="padding:10px;">
<p>{{testStr}}</p>
</body>
</html>
本質上,我正在初始化一個稱為test的變量,並將該變量綁定到testStr
范圍。 如果我在run()
上更新測試變量,則testStr在視圖中更新。 但是,如果我通過$http.get
請求更新同一變量,則視圖將永遠不會更新。 為什么是這樣? 完成這項任務的最佳方法是什么?
任何啟發都將不勝感激。
安瓜v1.2.16
我不認為您的問題與Angular有關。 test
和testStr
只是普通的舊JavaScript字符串,因此當您將其設置為等於新字符串時,它將創建一個新變量,並且不會影響任何其他變量。 如果要讓多個變量引用同一字符串,則必須將其放入對象中。 例如:
var a = {str: 'my string'}
var b = a;
b.str = 'new string';
//now a.str and b.str both equal 'new string'
您看到在run()
塊中所做的更改的唯一原因是因為它在$scope.testStr = test;
之前執行$scope.testStr = test;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.