I am not sure why no one has yet suggested bindToController
which removes all these ugly scopes and $watches.
If You are using Angular 1.4
Below is a sample DOM:
<div ng-app="app">
<div ng-controller="MainCtrl as vm">
{{ vm.name }}
<foo-directive name="vm.name"></foo-directive>
<button ng-click="vm.changeScopeValue()">
changeScopeValue
</button>
</div>
</div>
Follows the controller
code:
angular.module('app', []);
// main.js
function MainCtrl() {
this.name = 'Vinoth Initial';
this.changeScopeValue = function(){
this.name = "Vinoth has Changed"
}
}
angular
.module('app')
.controller('MainCtrl', MainCtrl);
// foo.js
function FooDirCtrl() {
}
function fooDirective() {
return {
restrict: 'E',
scope: {
name: '='
},
controller: 'FooDirCtrl',
controllerAs: 'vm',
template:'<div><input ng-model="name"></div>',
bindToController: true
};
}
angular
.module('app')
.directive('fooDirective', fooDirective)
.controller('FooDirCtrl', FooDirCtrl);
A Fiddle to play around, here we are changing the scope value in the controller
and automatically the directive updates on scope change
.
http://jsfiddle.net/spechackers/1ywL3fnq/