您好,欢迎访问一九零五行业门户网

三种AngularJS中获取数据源的方式

这篇文章主要介绍了三种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>
以上,把数据源放在$rootscope中的某个字段中,很容易被重写。
■ 数据源放在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>
在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"> <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;})
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注!
相关推荐:
js实现(全选)多选按钮的方法
angular hmr(热模块替换)功能的实现方法
关于angularjs中的$apply及优化使用
以上就是三种angularjs中获取数据源的方式的详细内容。
其它类似信息

推荐信息