使用模板表达式将范围变量传递给嵌套控制器

时间:2015-04-23 09:36:08

标签: javascript angularjs angularjs-scope controllers

首先,我要简单介绍一下我要完成的工作。我有我的firstController由ui-router发起。该控制器为我提供了一些基于页面的数据,在这种特定情况下,它是一个产品列表。

firstController包含$ scope.ids,它是一个产品ID的数组。它启动secondController,它充当产品列表的模型和视图。 secondController处理过滤,排序等功能,第四,firstController就是页面本身。

thirdController是实际的产品控制器。它针对每种产品运行,并检查变体,特殊折扣和优惠等等。第四。

我的问题:在启动thirdController之前不评估data-attr-id =“{{ids}}”,因此控制器将data-attr-id值读为{{ids}}而不是数组评估表达式时的数字。

我不希望将这些转换为指令。有什么建议吗?

<div ng-controller="firstController">

    <div ng-controller="secondController" data-attr-id="{{ids}}">

        <div ng-controller="thirdController" ng-repeat="product in productlist"></div>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

我不能从你上次的评论中理解为什么你使用三个控制器,所以我做了一个更简单的例子来帮助我们找到正确的解决方案 - Plunker

JS

var app = angular.module('plunker', []);

app.controller('firstController', function($scope) {
  $scope.$watch("products", function(newValue) {
    if (angular.isDefined(newValue)) {
      $scope.ids = "";
      for (var i = 0; i < newValue.length; i++) {
        $scope.ids += newValue[i].id + ", ";
      }
    }
  })
});

app.controller('secondController', function($scope) {
  $scope.getProducts = function() {
    $scope.products = [
      {id: "1", name: "product1"},
      {id: "2", name: "product2"},
      {id: "3", name: "product3"},
      {id: "4", name: "product4"},
      {id: "5", name: "product5"}
    ];
    $scope.$parent.products = $scope.products;
  }
});

app.controller('thirdController', function($scope) {
  $scope.$watch("$parent.products", function(newValue) {
    if (angular.isDefined(newValue)) {
      $scope.productList = newValue;
    }
  })
});

标记

  <div ng-controller="firstController">
    IDs: {{ids}}
    <div ng-controller="secondController">
        <button ng-click="getProducts()">Get products</button>
        <div ng-controller="thirdController">
          <div ng-repeat="product in productList">
            {{product.name}}
          </div>
        </div>
    </div>
  </div>