【问题标题】:Pass params in ng-include在 ng-include 中传递参数
【发布时间】:2015-07-23 07:04:31
【问题描述】:

我是 angularjs 的新手。我有一个要求,我在每个部分 html 中一次又一次地使用相同的单选按钮。所以,我想把它做成一个通用模板,用在其他部分模板中。

<ng-include src="'partial-htmls/toolbox/radio-button.html'"></ng-include>

其中显示单选按钮如下:

Sex :    O Male
         O Female

这很好,但我需要在ng-include 中以某种方式更改标签、文本和单选按钮的数量。 (我想通过某种方式传递参数来做到这一点)

我来自lodash的背景,可以轻松处理。我认为也可能有角度的方法。

请帮忙。

【问题讨论】:

  • 这看起来像是 ng-include 的奇怪用法。为什么不嵌套控制器?
  • @Amit 我想我应该使用ng-include 请建议我处理这个问题的最佳方法是什么。

标签: javascript html angularjs templates


【解决方案1】:

无法将参数传递给ng-include。
不过,它确实可以访问与其所在的 HTML 相同的范围。

如果您需要能够传递不同的参数,您将不得不使用指令:

angular.module("myModule")
.directive('radioButton', [function () {
    return {
        restrict: 'E',
        scope: {
            pass: "=",
            some: "@",
            properties: "="
        },
        templateUrl: 'app/directives/views/radio-row.html',
        controller: ["$scope", function ($scope) {
            // Isolated $scope here
        }]
    };
}]);
<radio-button pass="parentScopeObject" some="Literal string" properties="parentScopeSomething"></radio-button>

【讨论】:

  • 您可以将ng-controller 或ng-init 放在与ng-include 相同的元素上,但指令会更好。
  • 当我将自定义属性用单引号括起来时,这很有效。像这样:pass="'parentScopeObject'" some="'Literal string'" properties="'parentScopeSomething'"。谢谢!!
  • @Mr_Green:对于需要使用“@”的字符串,则不需要额外的引号。基本上,"@" 会从字面上获取传递参数的内容,"=" 会将参数解释为父作用域中的变量名。 This question explains that quite well.
猜你喜欢
  • 2014-10-23
  • 2018-07-21
  • 2014-10-29
  • 2011-10-11
  • 2017-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多