Search code examples
javascriptangularjsangularjs-scope

Angularjs: Object property value does not update


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.


Solution

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