...
function Order(object) {
object.parts = object.parts || [];
var partsArr = [];
object.parts.forEach(function (value, key) {
partsArr[key] = new Order(value);
});
this.name = object.name || 'Default';
this.cost = object.cost || 0;
this.parts = partsArr;
}
Order.prototype.summ = function() {
var summ = 0;
this.parts.forEach(function(part) {
summ += part.summ();
});
return summ + this.cost;
};
...
...
var Order = require('./order')
var myobject = new Order({name:'my object', cost: 10});
myobject.parts[0] = new Order({name:'my first part', cost: 20});
myobject.parts[1] = new Order({name:'my second part', cost: 30});
myobject.parts[1].parts[0] = new Order({name:'my first in second part', cost: 40});
...
...
<script src='order.js'></script> // здесь теги
...
var xhrobj = JSON.parse(this.responseText);
var myobject = new Order(xhrobj);
...
// создаем конструктор "класса" и нужные методы
function Order(name) {
this.name = name;
}
Order.prototype.addChild = function () {
this.parts = this.parts || [];
var levelName = this.name + '-' + (this.parts.length + 1);
this.parts[this.parts.length] = new Order(levelName);
};
Order.prototype.removeChild = function (index) {
if (index === undefined) {
delete this.parts;
} else if (index > -1 && index < this.parts.length) {
this.parts.splice(index, 1);
if (this.parts.length === 0) delete this.parts;
}
};
// имитация тех данных, которые приходят с сервера (в примере)
var prepareOrders = [];
prepareOrders[0] = new Order('part 1');
prepareOrders[0]['_id'] = '123456';
prepareOrders[1] = new Order('part 2');
prepareOrders[1]['_id'] = '234567';
// Вставляем в $scope
$scope.orders = prepareOrders;
<a href='' ng-click='$parent.$parent.part.removeChild($index)'>Remove this</a>
<a href='' ng-click='part.addChild()'>Add child</a>
<a href='' ng-click='part.removeChild()'>Remove childs</a>
// ...
link: function (scope, element) {
setTimeout(function () {
var html = '';
angular.forEach(scope.orders, function (ord) {
html += '<h4>' + ord.name + '</h4>';
});
element.append($compile(html)(scope));
console.log('end of directive');
}, 1000);
}
// ...
// ...
.directive('orderDrct', ['$compile', 'Order',
function ($compile, Order) {
return {
restrict: 'A',
link: function (scope, element) {
Order.query({id: 'all'}, function(orders) {
scope.orders = orders;
var html = '';
angular.forEach(scope.orders, function (ord) {
html += '<h4>' + ord.name + '</h4>';
});
element.append($compile(html)(scope));
});
}
};
}
])
// ...
Методы принимают следующие параметры:
HTTP GET "class" actions: Resource.action([parameters], [success], [error])
non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
non-GET instance actions: instance.$action([parameters], [success], [error])
Success вызывается с (value, responseHeaders) аргументами.
Error вызывается с (httpResponse) аргументом.