当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > 三种AngularJS中获取数据源的方式

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

2018年06月17日  | 移动技术网IT编程  | 我要评论

在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中获取数据源的方法,希望对大家的学习有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网