這篇文章主要介紹了三種AngularJS中取得資料來源的方式,需要的朋友可以參考下
在AngularJS中,可以從$rootScope中取得資料來源,也可以把取得資料的邏輯封裝在service中,然後注入到app.run函數中,或註入到controller中。本篇就來整理獲取資料的幾種方式。
#■ 資料來源放在$rootScope中
var app = angular.module("app",[]); app.run(function($rootScope){ $rootScope.todos = [ {item:"",done:true}, {item:"",done:false} ]; }) <p ng-repeat="todo in todos"> {{todo.item}} </p> <form> <input type="text" ng-model="newTodo" /> <input type="submit" ng-click=""todos.push({item:newTodo, done:false}) /> </form>
#■ 資料來源放在service中,把servie注入到run函數中
app.service("TodoService", function(){ this.todos = [ {item:"",done:true}, {item:"",done:false} ]; }) app.run(function($rootScope, TodoService){ $rootScope.TodoService = TodoService; }) <p ng-repeat="todo in TodoService.todos"> {{todo.item}} </p> <form> <input type="text" ng-model="newTodo" /> <input type="submit" ng-click=""TodoService.todos.push({item:newTodo, done:false}) /> </form>
<input type="submit" ng-click=""TodoService.todos.addodo(newTodo) />
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; })
<body ng-app="app" ng-controller="TodoCtrl as todoCtrl"> <p ng-repeat="todo in todoCtrl.TodoService.todos"> {{todo.item}} </p> </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; })
############################### ######
以上是三種AngularJS中取得資料來源的方式的詳細內容。更多資訊請關注PHP中文網其他相關文章!