Angularjs One way Binding Binds Data Two Way

770 Views Asked by At

I have a pseudo code like this where using the one-way-binding operator(::) I tried to see if angular is watching for changes. So I had to include it inside an input tag. the model data inside the input tag should be resolved one way because of :: before it. However if I make changes to the input and click the button to see the changes it reflects the changes in the log. But it should not watch for the changes.

<!DOCTYPE html>
<html ng-app="app">
<head>
    <meta charset="utf-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-animate.js"></script>
</head>
<body class="container" ng-controller="ItemsController">
    <ul ng-repeat="item in ::items">
        <li>
            <!-- in actual code the input will not be included -->
            <input type="text" ng-model="::item.name"> {{ ::item.name }}
            <!-- actual code -->
            <!-- {{ ::item.name }} -->
        </li>
    </ul>
    <button type="btn" ng-click="click()">Button</button>

    <script>
        angular.module('app', [])
        .controller('ItemsController', function ($scope) {
            $scope.items = [
                {name: 'item 1'},
                {name: 'item 2'},
                {name: 'item 3'}
            ];

            $scope.click = function () {
                for (var obj of $scope.items) {
                    console.log(obj.name);
                }
            };
        })
    </script>
</body>
</html>
1

There are 1 best solutions below

4
On

A couple of things.

Is one time, no one way bonding. Is useful when you want an expression to be evaluated only once and not watching for changes.

The :: in ng-model is doing nothing, it will still update the scope with the value that you put and update the item name.

At the same time the {{ ::item.name}} should remain unchanged, because is one time binding and it won't watch for additional changes.

So you will see the changes in the log, because the value actually changes, what will not change is the view.