Angular 2-way binding

2-way skips a cycle of digest

by vishwackh89

HTML

<div ng-app="myApp" ng-controller="Ctrl1">
    <button type="button" ng-click="myClick()">From Controller</button>
    <my-element my-attr="name" my-cnt="counter"></my-element>
    <div>{{name}}</div>
    <div>{{counter}}</div>
</div>

JavaScript

function Ctrl1($scope) {
    $scope.name = 'controller';
    $scope.counter = 0;

    $scope.myClick = function() {
        $scope.counter++;
        $scope.name = 'controller' + $scope.counter;
    }
}

angular.module('myApp', []).directive('myElement', function() {
    return {
        restrict: 'E',
        scope: {
            'myAttr': '=',
            'myCnt': '='
        },
        template: '<button ng-click="myOtherClick()">From Directive</button>',
        link: function(scope, iElement, iAttrs) {

            scope.myOtherClick = function() {
                scope.myCnt++;
                scope.myAttr = 'directive' + scope.myCnt;
            }
        }
    }
});