AngularJS - Simple Directive Use
HTML
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.angularjs.org/1.0.0/angular-1.0.0.js"></script>
<div ng-app="myApp">
<div my-directive>the value is {{something.value}}! <a href ng-click="changeIt()">click to change it</a>
</div>
</div>
CSS
.ui-state-highlight {
background-color: #EEEEEE;
}
JavaScript
angular.module('myApp', []).directive('myDirective',
function ($timeout) {
return {
link: function (scope, element, attrs) {
var elementHtml;
// Wait for the initial value
$timeout(function () {
elementHtml = element.html();
console.log(elementHtml);
// Start tracking when it changes
scope.$watch(htmlHasChanged, function (hasChanged) {
if (hasChanged) {
console.log('it changed!');
}
})
}, 0, false);
var htmlHasChanged = function () {
var newHtml = element.html();
if (newHtml !== elementHtml) {
elementHtml = newHtml;
return true;
}
return false;
};
scope.changeIt = function () {
scope.something.value = Math.random().toString(36).substring(10);
}
scope.something = {
value: 'foo'
}
}
};
});