Angular Directives - Service Factory
Share code between directives.
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<body ng-app="app">
<h3>Service Factory</h3>
<my-dir1 v1="a" v2="b" v3="c"></my-dir1>
<my-dir2 v1="a" v2="b" v3="c"></my-dir2>
<p />
<p>Press F12 and watch the console to see the update messages.</p>
</body>
CSS
/* change Wijmo widgets font to match bootstrap */
.ui-widget {
font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button {
font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;
}
/* use auto-width for Wijmo menu items */
.wijmo-wijmenu .wijmo-wijmenu-parent .wijmo-wijmenu-child {
width: auto;
min-width: 150px;
}
/* custom back color for Wijmo tooltips*/
.wijmo-wijtooltip {
background-color: #fff9d1;
}
JavaScript
// the module
var app = angular.module("app", []);
// first custom directive
app.directive("myDir1", ["myUtil", function (myUtil) {
return {
restrict: "E",
scope: {
v1: "@",
v2: "@",
v3: "@",
v4: "@",
v5: "@",
v6: "@"
},
template: "<div/>",
link: function (scope, element, attrs) {
var ctr = 0,
arr = ["v1", "v2", "v3", "v4", "v5", "v6"];
for (var i = 0; i < arr.length; i++) {
scope.$watch(arr[i], function () {
console.log("> updating my-dir1 " + ++ctr);
element.text(scope.v1 + scope.v2 + scope.v3 + scope.v4 + scope.v5 + scope.v6);
}, true);
}
}
}
}]);
// second custom directive
app.directive("myDir2", ["myUtil", function (myUtil) {
return {
restrict: "E",
scope: {
v1: "@",
v2: "@",
v3: "@",
v4: "@",
v5: "@",
v6: "@"
},
template: "<div/>",
link: function (scope, element, attrs) {
var ctr = 0,
arr = ["v1", "v2", "v3", "v4", "v5", "v6"];
myUtil.watchScope(scope, arr, updateFn);
function updateFn() {
console.log("# updating my-dir2 " + ++ctr);
element.text(scope.v1 + scope.v2 + scope.v3 + scope.v4 + scope.v5 + scope.v6);
}
}
}
}]);
// utilities shared by all directives
app.factory("myUtil", function () {
return {
// watch for changes in scope variables
// call update function when all have been initialized
watchScope: function (scope, props, updateFn, updateOnTimer) {
// watch all variables in the props array,
// keep count of changes and start calling the update function fn
// only after all variables have been initialized.
...