AngularJS - 如何使用变量渲染部分?

时间:2013-07-25 16:31:01

标签: angularjs

例如,我在car-list.html中有一个部分,我想在几个地方用不同的汽车集合渲染它。也许是这样的:

<h1>All New Cars</h1>
<div ng-include="car-list.html" ng-data-cars="allCars | onlyNew"></div>

<h1>All Toyotas</h1>
<div ng-include="car-list.html" ng-data-cars="allCars | make:toyota"></div>

与普通包括的主要区别在于,部分不需要知道它所显示的汽车列表。它给出了一系列汽车,并显示它们。可能就像:

<!-- car-list.html -->
<div ng-repeat="car in cars" ng-controller="CarListControl">
    {{car.year}} {{car.make}} {{car.model}}
</div>

3 个答案:

答案 0 :(得分:25)

您可以使用directive轻松实现这一目标。

类似的东西:

angular.module('myModule')
.directive('cars', function () {
  return {
    restrict: 'E',
    scope: { 'cars': '=data' },
    template: "<div ng-repeat='car in cars'>\n" +
    "  {{car.year}} {{car.make}} {{car.model}}\n" +
    "</div>"
  };
});

然后你可以这样使用它:

<h1>All New Cars</h1>
<cars data="allCars | onlyNew"></cars>

<h1>All Toyotas</h1>
<cars data="allCars | make:toyota"></cars>

您可以找到有关指令here的更多信息。

答案 1 :(得分:16)

此指令提供父作用域与子作用域中重命名的“本地”变量之间的双向数据绑定。它可以与其他指令(如ng-include)结合使用,以获得出色的模板可重用性。需要AngularJS 1.2.x

jsFiddle:AngularJS - Include a partial with local variables


标记

<div with-locals locals-cars="allCars | onlyNew"></div>

发生了什么:

  • 这基本上是ngInclude指令的扩展,允许您从父作用域传递重命名的变量。完全不需要ngInclude,但此指令旨在与其配合使用。
  • 您可以附加任意数量的locals-*属性,这些属性都将被解析并且看着作为Angular表达
    • 这些表达式可用于包含的部分,附加为$scope.locals对象的属性。
    • 在上面的示例中,locals-cars="..."定义了一个可用作$scope.locals.cars的表达式。
    • 类似于使用data-cars="..."
    • 通过jQuery提供.data().cars属性的方式

指令

编辑我已经重构使用(并且独立于)本地ngInclude指令,并将一些计算移动到编译函数中以提高效率。

angular.module('withLocals', [])
.directive('withLocals', function($parse) {
    return {
        scope: true,
        compile: function(element, attributes, transclusion) {
            // for each attribute that matches locals-* (camelcased to locals[A-Z0-9]),
            // capture the "key" intended for the local variable so that we can later
            // map it into $scope.locals (in the linking function below)
            var mapLocalsToParentExp = {};
            for (attr in attributes) {
                if (attributes.hasOwnProperty(attr) && /^locals[A-Z0-9]/.test(attr)) {
                    var localKey = attr.slice(6);
                    localKey = localKey[0].toLowerCase() + localKey.slice(1);

                    mapLocalsToParentExp[localKey] = attributes[attr];
                }
            }

            var updateParentValueFunction = function($scope, localKey) {
                // Find the $parent scope that initialized this directive.
                // Important in cases where controllers have caused this $scope to be deeply nested inside the original parent
                var $parent = $scope.$parent;
                while (!$parent.hasOwnProperty(mapLocalsToParentExp[localKey])) {
                    $parent = $parent.$parent;
                }

                return function(newValue) {
                    $parse(mapLocalsToParentExp[localKey]).assign($parent, newValue);
                }
            };

            return {
                pre: function($scope, $element, $attributes) {

                    // setup `$scope.locals` hash so that we can map expressions
                    // from the parent scope into it.
                    $scope.locals = {};
                    for (localKey in mapLocalsToParentExp) {

                        // For each local key, $watch the provided expression and update
                        // the $scope.locals hash (i.e. attribute `locals-cars` has key
                        // `cars` and the $watch()ed value maps to `$scope.locals.cars`)
                        $scope.$watch(
                            mapLocalsToParentExp[localKey],
                            function(localKey) {
                                return function(newValue, oldValue) {
                                    $scope.locals[localKey] = newValue;
                                };
                            }(localKey),
                            true
                        );

                        // Also watch the local value and propagate any changes
                        // back up to the parent scope.
                        var parsedGetter = $parse(mapLocalsToParentExp[localKey]);
                        if (parsedGetter.assign) {
                            $scope.$watch('locals.'+localKey, updateParentValueFunction($scope, localKey));
                        }

                    }
                }
            };
        }
    };
});

答案 2 :(得分:3)

我想提供my solution,这是一个不同的设计。

您的理想用途是:

<div ng-include-template="car-list.html" ng-include-variables="{ cars: (allCars | onlyNew) }"></div>

ng-include-variables的对象被添加到本地范围。因此,它不会浪费您的全局(或父级)范围。

这是你的指令:

.directive(
  'ngIncludeTemplate'
  () ->
    {
      templateUrl: (elem, attrs) -> attrs.ngIncludeTemplate
      restrict: 'A'
      scope: {
        'ngIncludeVariables': '&'
      }
      link: (scope, elem, attrs) ->
        vars = scope.ngIncludeVariables()
        for key, value of vars
          scope[key] = value
    }
)

(这是在Coffeescript中)

IMO,ng-include有点奇怪。访问全局范围会降低其可重用性。