使用服务在角度控制器之间传递数据

时间:2016-01-05 01:57:18

标签: css angularjs ionic

我在使用服务的控制器之间传递数据时遇到问题。我想要发生的是当点击发送数据时,输入到文本字段的数据应该填充在结果控制器中。但没有显示

Home.html中:

   <html>
<body>
<ion-header-bar class="bar-dark">
    <h1 class="title"></h1>
</ion-header-bar>
<ion-view view-title="Home">
    <ion-content ng-controller="StockUpdateCtrl">

    <div class="list">         
<ion-refresher pulling-text="Pull to Refresh" on-refresh="doRefresh()"></ion-refresher>
    <div>{{text}}</div>
    <input type='text' ng-model='text' />

     <button type='button' ng-click='send()'>Send Data</button>
     <div ng-controller='ResultsController'>
  <div>
    <h4>Ctrl2</h4>
    <div>{{text}}</div>
  </div>
</div>
    </ion-content>

</ion-view>
    </body>
    </html>

HomeController.js:

var app = angular.module('starter', ['ionic'])


        .run(function ($ionicPlatform) {
            $ionicPlatform.ready(function () {
                // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
                // for form inputs)
                if (window.cordova && window.cordova.plugins.Keyboard) {
                    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                }
                if (window.StatusBar) {
                    StatusBar.styleDefault();
                }
            });
        })


/*
 * Data Service 
 * Service used to pass data between controllers
 */
app.factory('dataShare', function(){
   var service = {};
  service.data = false;
  service.sendData = function(data){
      this.data = data;
      $rootScope.$broadcast('data_shared');
  };
  service.getData = function(){
    return this.data;
  };
  return service;
});

/* 
 * Stock Update Controller
 * Gets user input and then performs calculations to prepare to be displayed
 * 
 */
app.controller("StockUpdateCtrl", function ($scope, $http, dataShare) {


    $scope.text = 'Hey';
         $scope.send = function(){
           dataShare.sendData($scope.text);
         };



});

ResultsController.js:

 * Resultse Controller
 * Displays the results
 * 
 */
app.controller("ResultsController",function ($scope, dataShare) {

    $scope.text = '';
                $scope.$on('data_shared',function(){
                            var text =  dataShare.getData();    
              $scope.text = text;
        });
});

1 个答案:

答案 0 :(得分:0)

哈哈明白了。是的,事实证明这是我调用结果页面的方式......我不得不删除表单标签

<form action="index.html#/results" ng-controller="StockUpdateCtrl">

并更改我的按钮以调用结果页面

<button type="submit" ui-sref="results"  ng-click="calculate()" class="button button-block button-balanced">