无法使用angularjs中的工厂将范围数据获取到html页面

时间:2016-02-17 05:01:27

标签: angularjs

我能够将相同的json数据从home.js发送到content.js.But我无法将content.js范围数据填充到html页面

任何人都可以帮我解决这个问题...

我的家.js:

angular.module('myApp')
   .controller('firstCtrl', ['$scope', 'myService',
                            function ($scope,myService) {

  $scope.list1= [];
         $scope.list2= [];

 var sampleItem = this.item;
            myService.setJson(sampleItem);

 $.each($scope.samples, function (i, x) {
                  if (x.name === sampleItem .secName && x.id === sampleItem .id) {

                     if (sampleItem .secName === $scope.secsList[0]) {

                        $scope.list1.push(x);


                     } 
                     else {

                        $scope.list2.push(x);
                     }
                     $scope.myData = x.dataList;


                  }
               });
               });

我的内容.js:

 angular.module('myApp')
    .controller('secondCtrl', function ($scope,myService) {

      $scope.myreturnedData = myService.getJson();

        console.log($scope.myreturnedData);

    })

  .factory('myService', function(){
    var sampleItem = null;
     return {
     getJson:function(){
       return sampleItem;
     },
     setJson:function(value){
      sampleItem = value;
     }
     }

});

我的content.html:

  <div ng-controller="secondCtrl" > {{myreturnedData.sampleName}}</div>

我的home.html:

<div ng-controller="firstCtrl" ng-repeat="item in list1" >
                        <div > {{item.sampleName}} </div>
                        </div>

1 个答案:

答案 0 :(得分:1)

这是工作解决方案jsfiddle

angular.module('ExampleApp',[])
  .controller('firstCtrl', function($scope, myService) {

      $scope.sampleItem = {
        sampleName: "sampleName"
      };
      myService.setJson($scope.sampleItem);
    }
  )
  .controller('secondCtrl', function($scope, myService) {

    $scope.myreturnedData = myService.getJson();

    console.log($scope.myreturnedData);

  })
.factory('myService', function() {
  var sampleItem = null;
  return {
    getJson: function() {
      return sampleItem;
    },
    setJson: function(value) {
      sampleItem = value;
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="firstCtrl">
  <h2>
  firstCtrl
  </h2>
    <input ng-model="sampleItem.sampleName">
  </div>
  <div ng-controller="secondCtrl"> <h2>
  secondCtrl
  </h2>{{myreturnedData.sampleName}}</div>
</div>