gpt4 book ai didi

jquery - 如何创建包含不同数据的 `directive` 的多个实例

转载 作者:行者123 更新时间:2023-12-01 02:54:11 26 4
gpt4 key购买 nike

我在$scope中有数据,根据范围classNames计数,我需要在页面中使用与范围不同的数据创建元素。怎么办?

我正在尝试添加更多 no.of directive 元素,但我只看到一个输出。我无法将 $scope 数据传递给它。

正确的做法是什么?

这是我的尝试:

<div class="wrapper" ng-app="myApp">
<div class="helloWorld" ng-controller="hello">
<ul>
<li ng-repeat="item in items">
{{item.name}}
</li>
</ul>
<hello-world/> //added multiple times
<hello-world/>
<hello-world/>
<hello-world/>
<hello-world/>
</div>

</div>

var app = angular.module('myApp', []);

app.controller('hello', function ($scope) {
$scope.items = [
{name:'name1', className:'green'},
{name:'name2', className:'blue'},
{name:'name3', className:'brown'},
{name:'name4', className:'yellow'},
{name:'name5', className:'red'}
];
});

app.directive('helloWorld', function () {
return {
restrict: 'AE',
replace: 'true',
template: '<h3 class="{item.className}">Hello World!! from color of {{item.className}}</h3>',
scope: {
className: '@'
},
link : function ($scope, elem, attr) {
}
}
});

jsfiddle

任何人都可以帮助我理解这个概念并在此处创建指令的多个实例吗?

提前致谢。

最佳答案

..I am trying to add more no.of directive element, But i see only one output.

首先,您需要正确关闭指令标签。使用所以<hello-world><hello-world/>而不是<hello-world/> 。另外,将该指令放入 ng-repeat 中以获取多个元素。

        <li ng-repeat="item in items">
{{item.name}}
<hello-world class-name="{{item.className}}"></hello-world>
</li>

and i am not able to pass the $scope data to it.

这是因为您为指令创建了“隔离范围”!

  scope: {
className: '@'
}

@符号表示className在隔离范围内将从属性 class-name 获取其值在指令中

app.directive('helloWorld', function () {
return {
restrict: 'E',
replace: 'true',
template: '<h3>Hello World!! from color of "{{className}}"</h3>',
scope: {
className: '@'
},
link: function ($scope, elem, attr) {}
}
})

这是dmeo

关于jquery - 如何创建包含不同数据的 `directive` 的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30747998/

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