var app = angular.module('demo', []); app.controller('DemoCtrl', function($scope) { $scope.reset = function() { $scope.data = { email: '[email protected]' }; }; $scope.reset(); }); app.directive('myDirective', ['$parse', function($parse) { return { restrict: 'A', scope: true, link: function(scope, iElement, iAttrs) { var attrModel = $parse(iAttrs.myDirective) function updateContents() { // get value from the attribute and update directive contents iElement.html('directive: ' + attrModel(scope)); } scope.$watch(attrModel, function(newValue) { // watch the attribute model updateContents(); }); scope.changeValue = function(newValue) { // assign value to the attribute model attrModel.assign(scope, newValue); updateContents(); } updateContents(); } } }]);
<h3>Attribute bind demo</h3> <div ng-controller="DemoCtrl"> scope: {{ data.email }} <button ng-click="reset()">reset</button> <br><br> <div data-my-directive="data.email" ng-click="changeValue('[email protected]')">Click me to change the email </div> <br><br> Click the directive to change the scope value </div>