【问题标题】:Angular Js ng-repeat with custom directive templateUrl带有自定义指令templateUrl的Angular Js ng-repeat
【发布时间】:2023-04-05 13:05:02
【问题描述】:

我在带有模板 url 的 angular js 中使用自定义指令,代码链接是 here。问题是,如果我将 ngRepeat 传递给元素,那么 ngRpeat 不能使用模板 url,那么它就不起作用,但是如果我传入模板本身,它就可以工作。

【问题讨论】:

  • 添加问题

标签: angularjs angularjs-directive custom-directive


【解决方案1】:

更新:

以下是您在 main.html 中编写的代码

<search-results customers-d ="customers" ng-repeat="CM in customersD></search-results>

以下是您编写的指令 searchResults:

myApp.directive('searchResults', function () {
    return {
        templateUrl: 'directives/search.html',
        scope: {
            customersD: '=',
        }
    }
});

以下是您编写的主控制器:

myApp.controller('mainController', ['$scope', '$log', function($scope, $log) {
    $scope.customers = [{ name:'Rishabh'},{name:'Krishna'}]
}]);

而search.html如下:

<a href="#" class="list-group-item">
    <h4 class="list-group-item-heading"> hi </h4>
    <p class="list-group-item-text">{{CM.name}}</p>
</a>

现在你做错了:

  1. main.html 的 ng-repeat 中缺少结束引号
  2. 试图访问 main.html 中的 customersD,而 mainController 的 $scope 中没有定义名为 customersD 的数组。
  3. 试图访问 search.html 中的 CM(它是隔离范围指令的模板)。 search.html 中只能有customersD

我认为您对范围的理解不正确。如果您在此处提问之前阅读足够多的内容会很好。 :)

上一个答案: 您在 ng-repeat 中缺少右引号并使用了错误的变量 执行以下操作:

<search-results customers-d ="CM" ng-repeat="CM in customers"></search-results>

【讨论】:

  • 添加了引号和你的变量仍然没有显示名称,并且请解释更改变量的原因
  • 嗨 Pranav 感谢您的回复!你的第二点说试图访问main.html中的customersD,而mainController的$scope中没有定义名为customersD的数组。但这就是为什么我定义了正在访问客户对象的customersD
  • customers-d ="customers"customers 对象传递给指令,并且可以使用 customersD 在指令中访问,但您尝试 ng-repeat 的数组是 customersD,它不在 mainController 的范围内.所以没有执行循环,也没有显示任何内容。
【解决方案2】:

main.html

<div class="list-group">
    <search-results customers-d ="customers" ng-repeat="CM in customers"></search-results>
</div>

app.js 中的指令更改

myApp.directive('searchResults', function () {
return {
    restrict : "AE",
    templateUrl: 'directives/search.html'
}
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2023-03-05
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多