Created
February 7, 2016 07:48
-
-
Save karataev/4142050b3b918fcbd6df to your computer and use it in GitHub Desktop.
Add/remove items by using directives with isolated scopes and a service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('app', []) | |
.controller('AppCtrl', ['Items', function (Items) { | |
var vm = this; | |
vm.items = Items.getAll(); | |
vm.addNewItem = function () { | |
Items.addNewItem(); | |
}; | |
}]) | |
.factory('Items', [function () { | |
var ID = 0; | |
var items = []; | |
function getAll() { | |
return items; | |
} | |
function addNewItem() { | |
items.push({ | |
id: ID | |
}); | |
ID++; | |
} | |
function removeItem(item) { | |
var index = items.indexOf(item); | |
items.splice(index, 1); | |
} | |
return { | |
getAll: getAll, | |
addNewItem: addNewItem, | |
removeItem: removeItem | |
} | |
}]) | |
.directive('ekItem', ['Items', function (Items) { | |
function controller() { | |
var vm = this; | |
vm.remove = function () { | |
Items.removeItem(vm.item); | |
} | |
} | |
return { | |
scope: {}, | |
bindToController: { | |
item: '=' | |
}, | |
controller: controller, | |
controllerAs: 'ctrl', | |
templateUrl: 'ek-item.html' | |
} | |
}]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Title</title> | |
</head> | |
<body ng-app="app" ng-controller="AppCtrl as ctrl"> | |
<h3>Добавление/удаление элементов с использованием директив с изолированной областью видимости и сервиса</h3> | |
<button ng-click="ctrl.addNewItem()">Добавить элемент</button> | |
<ek-item ng-repeat="item in ctrl.items" item="item" ></ek-item> | |
<script type="text/ng-template" id="ek-item.html"> | |
<div> | |
<span>Item id: {{ctrl.item.id}}</span> | |
<button ng-click="ctrl.remove()">Удалить</button> | |
</div> | |
</script> | |
<script src="../bower_components/angular/angular.js"></script> | |
<script src="app.js"></script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment