gpt4 book ai didi

angularjs - Angular 指令只重复最后一个元素

转载 作者:行者123 更新时间:2023-12-01 23:42:53 24 4
gpt4 key购买 nike

我正在尝试创建一个“工具”指令。我在 index.html 中添加了三种乐器,但我没有显示所有乐器,而是看到最后一种乐器重复了三次: enter image description here

/**
* Created by Shalmu Y. on 26.05.2015.
*/
/* @flow */
"use strict";
(function () {
const app = angular.module('Lesson3', []);
app.directive('instrument', function () {
return {
restrict:'E',
link: function (scope, el, attr) {
function cap(s){ return s.charAt(0).toUpperCase()+ s.substr(1); }
scope.strain = cap(attr.kind);
scope.caption = cap(attr.name);
},
template:'<span style="padding:4px; border:2px dotted #080;">{{strain}} - {{caption}}</span>'
};
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<!-- Created by Shalmu Y. on 26.05.2015 -->
<html ng-app="Lesson3">
<head lang="en">
<link rel="stylesheet" type="text/css" href="styles/style.css">
<meta charset="UTF-8">
<title>Lesson 3</title>
</head>
<body>
<instrument kind="brass" name="trumpet"></instrument>
<instrument kind="string" name="guitar"></instrument>
<instrument kind="woodwind" name="clarinet"></instrument>
</body>
</html>

最佳答案

指令中没有作用域,因此使用了父作用域。所以实际上你只有一个 scope.strain 和 scope.caption。

你可以做的是添加指令:

scope : {
strain: '=kind',
caption: '=name'
}

删除链接函数并在指令模板中使用大写过滤器。

Demo Plunkr

关于angularjs - Angular 指令只重复最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30488625/

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