首页 > 代码库 > ionic 不同view的數據交互

ionic 不同view的數據交互

angular中通過service factory 等服務來對不同的控制器進行數據交互 ,ionic 也一樣...

 1 var app = angular.module(‘ionicApp‘, [‘ionic‘]) 2  3 app.service(‘TodosService‘, function($q) { 4   return { 5     todos: [ 6       { 7         id: ‘1‘, 8         name: ‘Pick up apples‘, 9         done: false10       },11       {12         id: ‘2‘,13         name: ‘Mow the lawn‘,14         done: true15       }16     ],17     getTodos: function() {18       return this.todos19     },20     getTodo: function(todoId) {21       var dfd = $q.defer()22       this.todos.forEach(function(todo) {23         if (todo.id === todoId) dfd.resolve(todo)24       })25 26       return dfd.promise27     }28 29   }30 })

在不用的view中我們可以通過 route 中的resolve 來加載相關的服務;

 1 app.config(function($stateProvider, $urlRouterProvider) { 2   $urlRouterProvider.otherwise(‘/todos‘) 3  4   $stateProvider 5   .state(‘todos‘, { 6     url: ‘/todos‘, 7     controller: ‘TodosCtrl‘, 8     templateUrl: ‘todos.html‘ , 9     resolve: {10       todos: function(TodosService) {11         return TodosService.getTodos()12       }13     }14   })15   .state(‘todo‘, {16     url: ‘/todos/:todoId‘,17     controller: ‘TodoCtrl‘,18     templateUrl: ‘todo.html‘   ,19     resolve: {20       todo: function($stateParams, TodosService) {21         return TodosService.getTodo($stateParams.todoId)22       }23     }24   })25 })

在控制器中注入 在route中加載的服務返回的函數 如todo todos

1 app.controller(‘TodosCtrl‘, function($scope,todos) {2   $scope.todos = todos;3 })4 5 app.controller(‘TodoCtrl‘, function($scope,todo) {6 7   $scope.todo = todo8 9 })

 

這是鏈接 轉載於這個

ionic 不同view的數據交互