Angularjs,控制器无法从工厂读取?

时间:2016-07-08 06:19:10

标签: angularjs ionic-framework

我有一个services.js文件,我放置了我的facotry:

.factory('dataShare',function($rootScope){

 var service = {};
  service.data = false;
  service.sendData = function(data){
      this.data = data;
      $rootScope.$broadcast('data_shared');

  };
  service.getData = function(){
    return this.data;
      console.log('this.data')
  };
  return service;

})

我的控制器在controller.js文件中看起来像这样:

 .controller('recommendedJobsCtrl', function($q,$scope, $ionicSideMenuDelegate,$window,$http,dataShare) {

$scope.text='hey';
 $scope.post=function(){
dataShare.sendData($scope.text);
 console.log('here')
  }   

})
.controller('jobPostCtrl', function($scope,$ionicSideMenuDelegate,dataShare) {
  $scope.text = '';
 $scope.$on('data_shared',function(){
var text =  dataShare.getData();    
$scope.text = text;
console.log(text)
       });
})

当我执行console.log时,我意识到service.getData没有工作,即接收控制器(jobPostCtrl)没有得到任何东西。 我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

这是有效的例子。

<!doctype html>
<html>
    <head>
        <title>AngularJS</title>
        <script src="angular.min.js"></script>
        <script type="text/javascript">
            var sampleApp = angular.module('sampleApp', []);

            sampleApp.factory('dataShare',function($rootScope){
                var service = {};
                service.data = false;
                service.sendData = function(data){
                    this.data = data;
                    $rootScope.$broadcast('data_shared');
                };
                service.getData = function(){
                    return this.data;
                    console.log('this.data')
                };
                return service;
            });

            sampleApp.controller('recommendedJobsCtrl', function($q,$scope,$window,$http,dataShare) {
                $scope.text='hello world!';
                $scope.post=function(){
                    dataShare.sendData($scope.text);
                    console.log('sent: ' + $scope.text);
                }   
            });

            sampleApp.controller('jobPostCtrl', function($scope,dataShare) {
                $scope.text = '';
                $scope.$on('data_shared',function(){
                    var text =  dataShare.getData();
                    $scope.text = text;
                    console.log('received: ' + $scope.text);
                });
            });
        </script>
    </head>
    <body ng-app="sampleApp">
        <div ng-controller="recommendedJobsCtrl">
            <input type="text" ng-model="text" />
            <button ng-click="post()">Send</button>
        </div>
        <div ng-controller="jobPostCtrl">
            <p>{{text}}</p>
        </div>
    </body>
</html>

答案 1 :(得分:0)

使用 $ $ rootScope广播(&#39; data_shared&#39;,this.data);

和$ scope。$ on(&#39; data_shared&#39;,功能(事件,数据){

$ $范围= scope.text数据;

});