0

I know there are multiple questions related to my issue, but I still have problem fixing this. I have the following html and JavaScript code:

<!doctype html>
<html ng-app="Demo">
<head>
    <meta charset="utf-8" />
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous">      
    </script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">     
    </script>

</head>
<body ng-controller="AppController">

        <input type="" name="" ng-model="docs[1].value">
        {{m3.value}}
        {{m4}}

    <script type="text/javascript">
        var app = angular.module('Demo', []);

        app.controller(
            "AppController",
            function( $scope ) {

                $scope.docs=[{value:"first doc"}, {value:"second doc"}];                

                $scope.m3=$scope.docs[1]; 
                $scope.m4=$scope.docs[1].value;

            }
        );


    </script>

</body>
</html>

When I type in the input, the m3.value gets updated but m4 does not! I can't figure out why this is happening. Any comment is appreciated.

2 Answers 2

4

Statement 1 :

$scope.m3=$scope.docs[1];

This statement storing the reference for model docs[1]

so, {{m3.value}} will get updated model value.

Statement 2 :

$scope.m4=$scope.docs[1].value; 

This statement copying the actual primitive value.

so, {{m4}} still get old value

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

5 Comments

Thanks, but how should I bind to the docs[1].value in the controller then?
@user1512681 you can use $scope.docs[1].value or m3.value to get the updated value in controller
(off topic) is it still a two-way binding? will it be part of watchers?
@RIYAJKHAN $scope.docs[1].value does not give me the updated value.
@user1512681 check this one . plnkr.co/edit/sZ2hKSzolTOzZG6HcupN?p=preview
1

Ok so the way I solved it is to add a watcher to m3.value:

$scope.$watch('m3.value', function(){
     console.log('Changing');
     $scope.m4 = $scope.m3.value;
});

And now $scope.m4 updates.

2 Comments

This is the only way that worked for me, the ng-change that you suggested does not fit to what I want. Please note that the code I provided here is a simplified version of my original code
I shown ng-change just to show you that modal is updating and not suggested for your code use

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.