gpt4 book ai didi

javascript - 循环遍历angularjs中的嵌套指令

转载 作者:行者123 更新时间:2023-11-30 13:09:59 25 4
gpt4 key购买 nike

我是 Angular 的新手,正在尝试进行一些指令嵌套,但遇到了一些问题。

这是我的代码:

module.controller("TimelineController", ["$scope", "$compile", function ($scope, $compile) {

$scope.text = "ohoh";
$scope.elements = ["12", "13"];

console.log("Timeline Controller", arguments);

}]);

module.directive('timeline', function() {
return {
restrict: 'E',
transclude: true,
scope: true,
controller : "TimelineController",
link: function(scope, element, attrs, controller) {
console.log("linking timeline", arguments);
},
templateUrl:'templates/directives/timeline.html',
replace: true
};
});

module.directive('timelineEvent', function() {
return {
restrict: 'E',
transclude: true,
scope: true,
// controller : "TimelineController",
link: function(scope, element, attrs/*, controller*/) {
console.log("linking element", arguments);
},
templateUrl:'templates/directives/timeline_element.html',
replace: false
};
});

我的模板:

时间轴.html :

<div class="timeline">
<p>
timeline {{text}}
</p>

<div ng-repeat="element in elements">
- event {{element }}
<timeline-event ng-model="{{element}}"/>
</div>

</div>

timeline_element.html :

<div class="element">
timeline element o/ \o
</div>

我的 index.html :

[...]
<body>

<timeline></timeline>

</body>

意想不到的结果:

timeline ohoh

- event 12
- event 13
timeline element o/ \o

预期的结果当然是:

timeline ohoh

- event 12
timeline element o/ \o
- event 13
timeline element o/ \o

为什么 ng-repeat 会执行成功,但嵌套指令调用只执行一次?它不应该能够在循环中使用指令吗?

最佳答案

三点说明。我不知道这些是否是原因(为此需要在 jsFiddle 中对其进行测试),但它们肯定会破坏某些东西:

  • 为什么要设置transclude: true?您不在模板中使用 ng-transclude。您不需要 transclude: true

  • timeline 上的 ng-model 应该是 element 而不是 {{element}}

  • 您正在使用 scope: true,这意味着将创建一个新的范围。您可能需要定义您的范围(在您的两个指令上)。

因此:

scope: {
element: '&' // provides a way to execute an expression in the context of the parent scope.
}

关于javascript - 循环遍历angularjs中的嵌套指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14243017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com