Angular 1.5 Two-Way Binding

by Peter Drinnan

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="Ctrl1">
    <button type="button" ng-click="myClick()">From Component</button>
    <my-directive my-attr="name" my-cnt="counter"></my-directive>
	<my-component my-attr="name" my-cnt="counter"></my-component>
    <div>{{name}}</div>
    <div>{{counter}}</div>
</div>

JavaScript

angular.module('myApp', [])
    .controller('Ctrl1', function($scope) {
        $scope.counter = 0;
        $scope.name = 'controller ctor ' + $scope.counter;

        $scope.myClick = function() {
            $scope.counter++;
            $scope.name = 'controller ' + $scope.counter;
        }
    })
    .directive('myDirective', 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;
                }
            }
        }
    })
    .component('myComponent', {
        bindings: {
            'myAttr': '=',
            'myCnt': '='
        },
        template: '<button ng-click="$ctrl.myOtherClick()">From Component</button>',
        controller: function() {
            var self = this;

            self.myOtherClick = function() {
                self.myCnt++;
                self.myAttr = 'component ' + self.myCnt;
            }
        }
    });