Javascript 如何使用业务逻辑扩展已解析的$资源
我有下面的场景 服务: 路由器 控制器 到目前为止一切正常。我的控制器中有该项。现在我想用我的业务逻辑扩展$scope.item 业务逻辑 目标是: 以角度方式使用业务逻辑扩展$scope.item 我尝试使用angular.extend,但不起作用$scope.item不具有totalPrice函数 例如:在控制器中 问题 如何优雅地获得$scope.item包含item类的方法 编辑 @Ryeball提出的解决方案产生了一种丑陋的效果 现在“$scope.item”将$resource包装在“$scope.item.item”中 因此,我应该更改文档中的每个绑定路径 从…起 这解决了最后一个问题,但产生了新的问题 现在$scope.item不包含$resource方法。例如$scope.item.update due\uuuuu proto\uuuuuuu从资源更改为项目 最后 尽管$socpe.item不再具有更新和创建方法。可以改用itemApiJavascript 如何使用业务逻辑扩展已解析的$资源,javascript,angularjs,Javascript,Angularjs,我有下面的场景 服务: 路由器 控制器 到目前为止一切正常。我的控制器中有该项。现在我想用我的业务逻辑扩展$scope.item 业务逻辑 目标是: 以角度方式使用业务逻辑扩展$scope.item 我尝试使用angular.extend,但不起作用$scope.item不具有totalPrice函数 例如:在控制器中 问题 如何优雅地获得$scope.item包含item类的方法 编辑 @Ryeball提出的解决方案产生了一种丑陋的效果 现在“$scope.item”将$resource包装在
if ($scope.item._id) {
itemsApi.update({ id: $scope.item._id}, $scope.item)
.$promise.then(function(item) {
$scope.item = new Indoor(item);
});
} else {
itemsApi.create($scope.item)
.$promise.then(function(item) {
$scope.item= new Indoor(item);
});
}
为项目模型创建factory服务,并将其注入解析中,然后将解析值作为项目对象返回 项目服务 路由器 控制器 HTML
当你说它不起作用时,你是什么意思?$scope.item没有totalPrice函数?我已经编辑了答案,只是在get方法调用之后链接$promise属性。
$routeProvider
.when("/item/:id", {
templateUrl: "item.tpl.html",
controller: "ItemController",
resolve: {
item: ['$route', 'itemsApi', function ( $route, itemsApi) {
return itemsApi.get({ id: $route.current.params.id });
}]
}
}
})
.controller('ItemController',['$scope','item', function($scope, item) {
$scope.item = item;
}
function Item() {}
Item.prototype.totalPrice = function() {
// $scope.item should be here 'this'
return this.price + this.shipping;
}
$scope.item = angular.extend(item, new Item());
<span ng-bind="item.price"></span>
<span ng-bind="item.item.price"></span>
var Item = function Item(item) {
// mixing
angular.extend(this, item);
};
if ($scope.item._id) {
itemsApi.update({ id: $scope.item._id}, $scope.item)
.$promise.then(function(item) {
$scope.item = new Indoor(item);
});
} else {
itemsApi.create($scope.item)
.$promise.then(function(item) {
$scope.item= new Indoor(item);
});
}
.factory('Item', function() {
var Item = function(item) {
this.item = item;
};
Item.prototype.totalPrice = function() {
return this.item.price + this.item.shipping;
};
return Item;
});
$routeProvider
.when("/item/:id", {
templateUrl: "item.tpl.html",
controller: "ItemController",
resolve: {
item: ['$route', 'itemsApi', 'Item', function ( $route, itemsApi, Item) {
return itemsApi.get({ id: $route.current.params.id })
.$promise.then(function(item) {
return new Item(item);
});
}]
}
}
});
.controller('ItemController', ['$scope', 'item', function($scope, item) {
$scope.item = item; // this is an Item Object
}]);
{{item.totalPrice()}}