繁体   English   中英

Angular JS $ http.get()$ scope问题

[英]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有关。 testtestStr只是普通的旧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.

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