【问题标题】:Angular Ui-Router | Accesing a scope variable in a view from controller, but not workingAngular UI 路由器 |从控制器访问视图中的范围变量,但不工作
【发布时间】:2016-01-25 03:52:56
【问题描述】:

我有这个plunkr。我定义了两个控制器:mainControlleritemsController。我想从视图访问范围变量 items,但我不能。

要重现,您需要先单击按钮 Populate Items,(数组项由 service 填充),您会在 service 中看到strong>console 值。然后点击按钮Say Hello !然后你会看到items是空的;但是,变量 tab 正在被访问。

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

【问题讨论】:

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


    【解决方案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

    【讨论】:

    • 这太棒了,也很有趣!再次感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多