gpt4 book ai didi

javascript - AngularJS - 使用 ng-repeat 的动态指令

转载 作者:行者123 更新时间:2023-11-29 21:36:41 26 4
gpt4 key购买 nike

我花了一段时间试图为此找到一个优雅的解决方案,虽然我有一个“有效”的解决方案,但感觉它并不是最简单或正确的做事方式。

所以,我的问题是……如何动态加载指令!对于某些情况,以下是我希望能够摆脱它的方式!除了模板加载之外,我没有包含路由或任何其他内容,我为下面的 Controller 分配了 ng-controller。

app.js

angular.module('myApp', [])

.controller('someController', ['$scope', function($scope) {
$scope.directives = ['myDirectiveA', 'myDirectiveB'];
}])

.directive('myDirectiveA', function() {
return {
template: '<p>Directive A, exciting.</p>'
};
})

.directive('myDirectiveB', function() {
return {
template: '<p>Directive B, equally as exciting.</p>'
};
});

template.html

<div ng-controller="someController">
<div ng-repeat="directive in directives">

<x-directive></x-directive> // Attempt 1
<x-{{directive}}></x-{{directive}}> // Attempt 2
<{{'x-' + directive}}></{{'x-' + directive}}> // Attempt 3

</div>
</div>

任何人都可以提供的任何建议将不胜感激,如果我做的事情显然很愚蠢,请原谅这是我第一次使用 Angular!

最佳答案

希望对你有帮助

for explain: you have to $compile your directive when you want to use it in other directive like ngRepeat or other custom directive...

        angular.module('myApp', [])

.controller('someController', ['$scope', function ($scope) {
$scope.directives = ['my-directive-a', 'my-directive-b'];
}])

.directive('directive', function ($compile) {
return {
restrict: "A",
scope: {
set: "="
},
link: function (scope, element) {
element.html("<div class=\" "+ scope.set +" \"></div>");
$compile(element.contents())(scope);
}
};
})

.directive('myDirectiveA', function () {
return {
restrict: "C",
template: '<p>Directive A, exciting.</p>'
};
})

.directive('myDirectiveB', function () {
return {
restrict: "C",
template: '<p>Directive B, equally as exciting.</p>'
};
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title></title>
</head>
<body ng-controller="someController">

<div ng-repeat="directive in directives">
<div directive set="directive"></div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</body>
</html>

关于javascript - AngularJS - 使用 ng-repeat 的动态指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34663047/

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