Angular中的模型和集合?

Eva*_*bbs 8 javascript backbone.js angularjs restangular

我来自Backbone,所以也许我的观点对此有偏见,但我很难看到在Angular中建模数据的最佳方法.双向数据绑定非常棒,但过去当我想拥有持久集合和模型类时我很困惑.

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

var users = new UserCollection();
users.fetch();
users.doSomethingCustom()
users.at(0).doSomethingModel();
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经查看了Restangular和ngActiveResource,似乎没有人提供与我预期相同的功能.

有没有我遗失的东西,或者我正在以非角度的方式思考这个问题?

编辑:我最终使我自己的模型/集合非常类似于Backbone的,如果它可以帮助任何人:https://github.com/evanhobbs/angular-models

mpm*_*mpm 4

这确实是一个非常有趣的问题,我希望人们思考解决方案。理论上,您可以坚持使用 Backbone 模型。它可能会带来性能成本,但是。没有理由它不起作用。

开发你的模型层,而不考虑 AngularJS。然后你必须扩展你的模型并在初始化函数中添加一个监听器,该监听器将触发 $rootScope。每当模型更改时 $apply,对于你可能使用的任何集合都是如此。喜欢 :

/*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);
    };

}
Run Code Online (Sandbox Code Playgroud)

和景色

<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>
Run Code Online (Sandbox Code Playgroud)

一些演示在这里

现在我认为,AngularJS 使用原始 js 哈希效果更好。但是如果您需要将某些内容从 Backbone 移植到 AngularJS,如果已经拥有强大的模型层,那么它可以是一个解决方案。

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