DDR爱好者之家 Design By 杰米

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

DDR爱好者之家 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
DDR爱好者之家 Design By 杰米