Note: I've reproduced my code here in JS Bin
I have a directive, that prints out an array of items to a web page. Suppose that the line 'console.log("added")' was actually complex logic, and that it was something we wanted the directive to do every time, regardless of the controller using it. It could make an AJX call to indicate, a new record have been added.
So I'm imagining there would be a function in the directive that does this. And instead of using "$scope.items" to add a new item, the controller would call this function in the directive. Unless there's a better way to do this, can you tell me how to approach this?
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-app="app">
<div ng-controller="MyCtrl">
<input type="text" ng-model="newitem.name"/>
<button type="button" ng-click="addNewItem(newitem)">Add Item</button>
<menu items="items"/>
</div>
</body>
</html>
JavaScript:
var app = angular.module("app", []);
app.controller('MyCtrl', function($scope) {
$scope.items = [
{name: "item1"},
{name: "item2"},
{name: "item3"},
{name: "item4"}
];
$scope.addNewItem = function(newItem) {
$scope.items.push(angular.copy(newItem));
console.log("added"); //PRETEND THIS IS COMPLEX LOGIC WE WANT MOVED TO DIRECTIVE
};
});
app.directive("menu", function(){
return {
restrict: "E",
scope: {
items: "="
},
template: "<div ng-repeat='item in items'>{{item.name}}</div>"
};
});