AngularJS中获取数据源的几种方式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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中获取数据源的几种方式的主要内容,如果未能解决你的问题,请参考以下文章