AngularJS中獲取資料來源的幾種方式

Darren Ji發表於2016-02-02

 

在AngularJS中,可以從$rootScope中獲取資料來源,也可以把獲取資料的邏輯封裝在service中,然後注入到app.run函式中,或者注入到controller中。本篇就來整理獲取資料的幾種方式。


■ 資料來源放在$rootScope中

 

var app = angular.module("app",[]);

app.run(function($rootScope){
    $rootScope.todos = [
        {item:"",done:true},
        {item:"",done:false}
    ];
})


<div ng-repeat="todo in todos">
    {{todo.item}}
</div>

<form>
    <input type="text" ng-model="newTodo" />
    <input type="submit" ng-click=""todos.push({item:newTodo, done:false}) />
</form>

 

以上,把資料來源放在$rootScope中的某個欄位中,很容易被重寫。

■ 資料來源放在service中,把servie注入到run函式中

 

app.service("TodoService", function(){
    this.todos = [
        {item:"",done:true},
        {item:"",done:false}
    ];
      
})

app.run(function($rootScope, TodoService){
    $rootScope.TodoService = TodoService;
})  

<div ng-repeat="todo in TodoService.todos">
    {{todo.item}}
</div>

<form>
    <input type="text" ng-model="newTodo" />
    <input type="submit" ng-click=""TodoService.todos.push({item:newTodo, done:false}) />
</form>

 

在html中似乎這樣寫比較好:

<input type="submit" ng-click=""TodoService.todos.addodo(newTodo) />

在service中增加一個方法:

app.service("TodoService", function(){
    this.todos = [
        {item:"",done:true},
        {item:"",done:false}
    ];
    
    this.addTodo = fucntion(newTodo){
        this.todos.push({item:newTodo, done:false})
    }
      
})

 

■ 資料來源放在service中,把servie注入到controller中

 

app.controller("TodoCtrl", function($scope, TodoService){
    this.TodoService = TodoServce;
})

 

在對應的html中:

 

<body ng-app="app" ng-controller="TodoCtrl as todoCtrl">
    <div ng-repeat="todo in todoCtrl.TodoService.todos">
        {{todo.item}}
    </div>
</body>

<form>
    <input type="text" ng-model="newTodo" />
    <input type="submit" ng-click="todoCtrl.TodoService.addTodo(newTodo)"/>
</form>

 

■ 資料來源放在service中,把servie注入到controller中,與服務端互動

在實際專案中,service還需要和服務端互動。

 

var app = angular.module("app",[]);

app.service("TodoService", function($q, $timeout){
    this.getTodos = function(){
        var d = $q.defer();
        
        //模擬一個請求
        $timeout(function(){
            d.resolve([
                {item:"", done:false},
                ...
            ])
        },3000);
        
        return d.promise;
    }
    
    this.addTodo = function(item){
        this.todos.push({item:item, done:false});
    }
})

app.controller("TodoCtrl", function(TodoService){
    var todoCtrl = this;
    
    TodoService.getTodos().then(function(result){
        todoCtrl.todos = result;
    })
    
    todoCtrl.addTodo = TodoService.addTodo;
})

 

相關文章