var myApp = angular.module('DemoApp', []);
myApp.directive('jnhMustache', [function () {
var declaration = {};
declaration.restrict = 'E';
declaration.scope = {
data : '&',
watch : '='
};
declaration.transclude = false;
declaration.link = function (scope, element, attrs) {
function render () {
var html = Mustache.render(scope.template, scope.data());
element.html(html);
};
scope.template = element.html();
element.html('');
scope.$watch(function () {
var result = scope.data()[scope.watch].length;
return result;
}, function () {
render();
}, false);
};
return declaration;
}]);
myApp.controller('ExampleController', function ($scope) {
$scope.myData = {
name: 'Jon Hartmann',
friends: [
'Gowtham',
'Kiran',
'Marshall'
]
};
$scope.watching = 'name';
$scope.addFriend = function () {
$scope.myData.friends.push('Aundrae');
};
});
<div ng-app="DemoApp">
<div ng-controller="ExampleController">
Name: <input type="text" ng-model="myData.name" /> <br />
<label>
<input type="radio" ng-model="watching" value="name" /> Name
</label>
<label>
<input type="radio" ng-model="watching" value="friends" /> Friends
</label>
<hr>
Control:
<pre>{{myData | json}}</pre>
Mustache:
<jnh-mustache data="myData" watch="watching">
<div ng-non-bindable>
<h1>{{name}}</h1>
<ul>
{{#friends}}
<li> {{.}}</li>
{{/friends}}
</ul>
</div>
</jnh-mustache>
<button ng-click="addFriend()">Add Friend</button>
</div>
</div>
External resources loaded into this fiddle: