20

例如,我有一个部分 in 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>
4

3 回答 3

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>

您可以在此处找到有关指令的更多信息。

于 2013-07-25T16:50:19.400 回答
17

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

jsFiddle:AngularJS - 包含局部变量的局部变量


标记

<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));
                        }

                    }
                }
            };
        }
    };
});
于 2013-07-26T08:40:03.393 回答
3

我想提供我的解决方案,它的设计不同。

最适合您的用法是:

<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
    }
)

(在咖啡脚本中)

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

于 2015-10-25T17:49:24.910 回答