Angular Ui-Router |在控制器的视图中访问范围变量,但不起作用

时间:2015-10-26 05:42:26

标签: javascript angularjs angular-ui-router angularjs-routing angularjs-controller

我有plunkr。我定义了两个控制器: mainController itemsController 。我想从视图中访问范围变量 items ,但我无法访问。

要重现,您需要先点击按钮 Populate Items ,(数组项目是从 service 填充)然后您请参阅 console 中的值。然后点击 Say Hello ! 按钮,您会看到项目为空;但是,正在访问变量 tab

我认为我没有以正确的方式应用控制器的定义。

1 个答案:

答案 0 :(得分:1)

updated and working plunker

我们需要的是数据共享:

How do I share $scope data between states in angularjs ui-router?

所以代替这个

  app.controller("itemsController", 
   function($rootScope, $scope, $state, $stateParams, Data) {
    $scope.items = []; // local reference, not shared

    $scope.getFromJson = function() {
      Data.get().then(function handleResolve(resp) {
        $scope.items = resp;
        console.log($scope.items);
      });
    };
  })

我们将填写共享参考 $scope.Model.items = resp;

  app.controller("itemsController", 
   function($rootScope, $scope, $state, $stateParams, Data) {

    $scope.getFromJson = function() {
      Data.get().then(function handleResolve(resp) {
        $scope.Model.items = resp;
        console.log($scope.Model.items);
      });
    };
  })

将挂在超级根家。所以,而不是:

$stateProvider
  .state("home", {
    abtract: true,
    url: "/home",
    resolve: {
      $title: function() {
        return 'Tab1';
      }
    },
    views: {
      "viewA": {
        templateUrl: "home.html"
      }
    }
  });

我们将拥有:

  .state("home", {
    abtract: true,
    url: "/home",
    resolve: {
      $title: function() {
        return 'Tab1';
      }
    },
    views: {
      "viewA": {
        templateUrl: "home.html",
        // HERE we do the magic
        // this is a super parent view
        // at which $scope we will have shared reference Model
        controller: function($scope){
          $scope.Model = {}
        }
      }
    }
  });

检查行动here