三种AngularJS中获取数据源的方式
时间:2020-11-11 10:57:31|栏目: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} ]; }) <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; })
以上就是AngularJS中获取数据源的方法,希望对大家的学习有所帮助。
栏 目:AngularJS
下一篇:angularJs中ng-model-options设置数据同步的方法
本文标题:三种AngularJS中获取数据源的方式
本文地址:http://www.codeinn.net/misctech/21277.html