gpt4 book ai didi

javascript - 在 Angular 中声明模型定义以与 RESTful "new"一起使用

转载 作者:行者123 更新时间:2023-11-29 19:49:53 24 4
gpt4 key购买 nike

有谁知道是否有以 angularjs angular.module() 样式声明模型定义的方法或最佳实践?我发现有必要为我导航到“/item/new”的事件定义一个框架模型定义——当执行“/item/”时,该表单对来自服务的项目有各种绑定(bind): id/edit”,但调用 new 时没有 Item,因为你没有到达服务。

我知道我可以简单地声明一个全局模型或一个名为“模型”的全局对象,我可以自己存储它们,但我很好奇是否有 Angular 用户有更好的解决方案?我希望有这样的事情:

angular
.module('appModels', [])
.model('item', function(){
// Perform some operations like u would in a factory
return {
name: '',
price: 0
}
});

或者更理想的是:

    return {
name: String,
price: Number
}

非常感谢

最佳答案

angular.module API公开了四种方法,这些方法提供了这种行为的微妙不同的实现:

  • module.value()
  • module.factory()
  • module.service()
  • module.provider()

This Google groups post给出了所有这些用例的相当清晰的概要。

This snippet显示了所有这些在一个小 Angular 应用程序的上下文中的运行情况。

我认为我不能为这些链接vis-a-vis添加太多这些功能相对于彼此的位置。但是,出于您的目的,您似乎想要执行“模型工厂”功能并接收执行该功能的结果:为此您可能需要 module.factory():

angular
.module('appModels', [])
.factory('item', function(){
return {
name: '',
price: 0
}
});

然后你可以像这样注入(inject)这个工厂(注意注入(inject)的对象是工厂函数返回的实例):

angular
.module('itemController', ['appModels'])
.controller('itemCtrl', function($scope, item) {
console.log(item.name);
console.log(item.price);
}

关于javascript - 在 Angular 中声明模型定义以与 RESTful "new"一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18050840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com