Custom Directive
http://angularjs.org/
HTML
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<div ng-controller="mainController">
score: {{vm.score}}
<div item-menu datasource="vm.customers" add="vm.addCustomer()"></div>
</div>
CSS
body {
padding: 20px;
}
JavaScript
'use strict';
angular.module('myApp',[])
.controller('mainController', function ($scope) {
var vm = this;
vm.customers = ['First','Second','Third'];
vm.score = 0;
vm.addCustomer = function() {
vm.score++;
}
}).directive('itemMenu',function() {
var template = '<button ng-click="vm.addItem()">add item</button>'+
'<ul><li ng-repeat="item in vm.items">{{item}}</li></ul>';
return {
restrict: 'A',
scope: {
datasource: '=',
add: '&'
},
controller: controller,
controllerAs: 'vm',
bindToController: true,
template: template
};
});
var controller = function($scope) {
var vm = this;
function init() {
vm.items = angular.copy($scope.datasource);
}
init();
vm.addItem = function() {
$scope.add();
vm.items.push('new one');
}
}