$watch in Angular JS

When you create databinding in somewhere in the application on a scope , angular automatically created a watch internally , means it will listen the changes in the variable you bind.

Example
angular.module('app', []);
angular.module('app').controller('ctrl', function ($scope) {
$scope.size = 100;

});
angular.module('app').directive('heightDynamic', function () {
return {
link: function (scope, el, attrs) {
scope.$watch(attrs['heightDynamic'], function (newVal) {
el.css('height', newVal + 'px');
});
}
}
});

10-25-2015 4-59-11 PM

10-25-2015 4-59-36 PM

when the the value of the model ‘size’ changes, the size automatically set as a height of that div element.

Custom Click directive event using Angular Js

You can easily create a custom click directive using link function in angular js.

html source
ang1
I have added a custom attribute named custom-click in the button element for handling the click event which is similar to angular ng-click. Now i am going to write a custom directive for this custom attribute.

angular.module('app', []);

angular.module('app').controller('myController', function ($scope) {
$scope.obj = { message: "Not Clicked" };
$scope.callMethod = function (p) {
p.message = "Clicked!!";
}
});

angular.module('app').directive("customClick", function ($parse) {
return {
link: function (scope, element, attrs) {
var func = $parse(attrs["customClick"]);
element.on('click', function () {
scope.$apply(function () {
func(scope);
});
});
}
}
});

when you clicked the button you can see the message ‘Clicked !!’ in the h1 tag.