0

I am trying to accomplish what seems should be a simple task but i'm stumped.

Here is the simplest example I could come up with.

<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>

Essentially I am initializing a variable called test and binding the variable to the testStr scope. If I update the test variable on run() the testStr updates in the view. But if I update that same variable via a $http.get request then the view never gets updated. Why is this? What is the best way to accomplish this task?

Any enlightenment is greatly appreciated.

Anguar v1.2.16

1 Answer 1

2

I don't think your issue is Angular related. test and testStr are just plain old JavaScript strings so when you set one to be equal to a new string it creates a new variable and won't effect any other variables. If you want multiple variables to have a reference to the same string you'd have to put it in an object. e.g.:

var a = {str: 'my string'}
var b = a;

b.str = 'new string';

//now a.str and b.str both equal 'new string'

The only reason you see the changes you make in the run() block is because it executes before $scope.testStr = test;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.