gpt4 book ai didi

javascript - Angular 中的模型和集合?

转载 作者:数据小太阳 更新时间:2023-10-29 04:44:12 25 4
gpt4 key购买 nike

我来自 Backbone,所以也许我的观点受到了偏见,但我很难看到在 Angular 中建模数据的最佳方式。 2 向数据绑定(bind)非常棒,但是当我想拥有持久的集合和模型类时,我感到很困惑。

我习惯于能够定义一个集合,比如用户,然后能够在我想用新模型更新它时调用 .fetch() 。我也可以在集合和每个模型上定义自定义方法。

var users = new UserCollection();
users.fetch();
users.doSomethingCustom()
users.at(0).doSomethingModel();

到目前为止,我已经研究过 Restangular 和 ngActiveResource,但它们似乎都没有提供我期望的那种功能。

我是否遗漏了什么,或者我正在以一种非 Angular 的方式思考这个问题?

编辑:如果对任何人有帮助,我最终制作了自己的模型/系列与 Backbone 的非常相似:https://github.com/evanhobbs/angular-models

最佳答案

这确实是一个很有趣的问题,希望大家思考一下解决办法。理论上,您可以坚持使用 Backbone 模型。它可能会产生性能成本,但没有理由不起作用。

开发你的模型层,而不考虑 AngularJS。然后你必须扩展你的模型并在你的初始化函数中添加一个监听器,它会触发 $rootScope。只要模型发生变化就应用,对于你可能的任何集合都是一样的使用。类似的东西:

/*global angular,Backbone*/
angular.module('ng')
.value('Backbone', Backbone)
.factory('AngularModel', function(Backbone, $rootScope) {
return Backbone.Model.extend({
initialize: function() {
this.on('all', function() {
if (!$rootScope.$$phase) {
$rootScope.$apply();
}
});
}
});
})
.factory('AngularCollection', function(AngularModel, $rootScope) {
return Backbone.Collection.extend({
model: AngularModel,
initialize: function() {
this.on('all', function() {
if (!$rootScope.$$phase) {
$rootScope.$apply();
}
});
}
});
});

function Main($scope, AngularCollection) {
$scope.collection = new AngularCollection([{
name: "foo"
}, {
name: "bar"
}, {
name: "baz"
}]);
$scope.addModel = function(model) {
$scope.collection.add(model);
};

}

和 View

<body ng-app ng-controller="Main">
<div ng-repeat="model in collection.models">{{model.get('name')}}</div>
<form name="model_form" ng-submit="addModel(model)">
<fieldset>
<legend>Add model</legend>
<label for="">Name</label>
<input type="text" ng-model="model.name" />
<input type="submit" />
</fieldset>

</form>
</body>

Some DEMO HERE

现在在我看来,AngularJS 与原始 js 哈希一起工作得更好。但是如果你需要将某些东西从 Backbone 移植到 AngularJS,如果已经有一个强大的模型层,它可能是一个解决方案。

编辑:它可能在没有昂贵的 $rootScope.$apply 的情况下工作,

关于javascript - Angular 中的模型和集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24187914/

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