angular js directive attribute defaults
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<script type="text/ng-template" id="category.html">
<li >
<input type="checkbox"
ng-model="category.selected"
ng-click="testInternal(category)">
<label >{{category.name}}</label>
<ul ng-show="category.categoriesDTO && category.categoriesDTO.length > 0">
<div class="subCategories"></div>
</ul>
</li>
</script>
<div ng-controller="offersController">
<ul>
<categories
collection="categories"
test="test(msg)" >
</categories>
</ul>
</div>
JavaScript
angular.module('myApp', [])
.directive('categories', function () {
return {
restrict: "E",
replace: true,
scope: {
collection: '=',
test: '&'
},
template: "<category ng-repeat='category in collection' category='category'></category>"
}
})
.directive('category', function ($compile) {
return {
restrict: "E",
replace: true,
scope: {
category: '=',
test: '&'
},
templateUrl: "category.html",
controller: function ($scope) {
$scope.testInternal = function (category) {
$scope.test({msg:'My category is: '+ category.name })
};
},
link: function (scope, element, attrs) {
if (angular.isArray(scope.category.categoriesDTO)) {
element.find('div').append(
" <categories test='test(msg)' collection='category.categoriesDTO'></categories>"
);
$compile(element.contents())(scope)
}
}
}
})
.controller('offersController', function ($scope)
{
$scope.test = function(msg) {
alert(msg);
}
$scope.categories = [
{
"name": "Women",
"categoriesDTO": [
{
"name": "Sub1",
"categoriesDTO": [
{
"name": "Sub2",
"categoriesDTO": [
{
"name": "Sub3",
"categoriesDTO": []
}
]
}
]
}
]
}
];
});