2013-02-05 45 views
1

如何管理與AngularJS的模型關係?在Ember中非常容易,但是如何在AngularJS中處理它,而不會產生大量雜亂的代碼?在AngularJS中管理模型關係

+0

你能舉一些例子嗎?在AngularJS中,您可以使用JavaScript對象進行操作,因此您可以直接引用其他對象,然後「監視」它們(不要忘記將「true」設置爲第二個參數)。還有依賴注入,所以你可以注入依賴對象(注意模塊的'value'方法) –

回答

2

我用https://github.com/klederson/ModelCore/這是非常簡單和易於使用的

var ExampleApp = angular.module('ExampleApp', ['ModelCore']); //injecting ModelCore 

ExampleApp.factory("Users",function(ModelCore) { 
    return ModelCore.instance({ 
    $type : "Users", //Define the Object type 
    $pkField : "idUser", //Define the Object primary key 
    $settings : { 
     urls : { 
     base : "http://myapi.com/users/:idUser", 
     } 
    }, 
    $myCustomMethod : function(info) { //yes you can create and apply your own custom methods 
     console.log(info); 
    } 
    }); 
}); 

然後,我只需要注入到我的控制器,並使用它

function MainCrtl($scope, Users) { 
    //Setup a model to example a $find() call 
    $scope.AllUsers = new Users(); 

    //Get All Users from the API 
    $scope.AllUsers.$find().success(function() { 
    var current; 
    while(current = $scope.AllUsers.$fetch()) { //fetching on masters object 
     console.log("Fetched Data into Master Object",$scope.AllUsers.$toObject()) //reading fetched from master 
     //or just get the fetched object itself 
     console.log("Real fetched Object",current.$toObject()) 
    } 
    });