1

I have a fiddle here:

http://jsfiddle.net/grL95/9/

angular.module('myApp', [])
.controller('Ctrl', function($scope) {
    $scope.name = 'Hello';
    $scope.myNumbers = [10, 20, 30];
    $scope.printNumbers = function() {
        console.log($scope.myNumbers);
    }
});

When I type in the input field, the text updates in 'real time'. However, when I hit print, the original numbers are being displayed in the console. How can I get the updated numbers to display?

2 Answers 2

1

The problem lies on the arrays due to the Javascript Scope problem. You see, when you change the variable value, it is passing by value, meaning that any changes to the variable is overshadowed (the $scope inside the controller creates a new variables). To overcome this, you will need to use pass by reference so that the updates are reflected in the console.log(), as follow:

HTML

<div ng-controller="Ctrl">
    <div ng-repeat="num in myNumbers">
        <input type="text" ng-model="num.value" />
        <div>current scope: {{num.value}}</div>
    </div>
    <button ng-click="printNumbers()">print</button>
</div>

Javascript

angular.module('myApp', [])
.controller('Ctrl', function($scope) {
    $scope.name = 'Hello';
    $scope.myNumbers = [{value: 10},{value: 20},{value: 30}];
    $scope.printNumbers = function() {
        console.log($scope.myNumbers);
    }
});

Result

Try inputting 100 in column 1

enter image description here

this results: (in web inspector)

enter image description here

The array [100, 20, 30] shows as expected.

PLAYGROUND

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

Comments

0

Seems like it is loosing the reference when we are using ng-repeat for a value. If you can use a object array then it works fine.

    angular.module('myApp', [])
    .controller('Ctrl', function($scope) {
        $scope.name = 'Hello';
        $scope.myNumbers = [{val:10}, {val:20}, {val:30}];
        $scope.printNumbers = function() {
            console.log($scope.myNumbers);
        }
});

http://jsfiddle.net/grL95/10/

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.