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

3

我正在尝试创建一个“instrument”指令。我已经在我的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>


我遇到了类似的问题,我通过在 return{} 中添加 scope:true 来解决。 - AndreaM16
1个回答

3
你的指令没有作用域,所以会使用父级作用域。实际上,你只有一个作用域:strain和caption。
你可以在指令中添加以下内容:
scope : {
  strain: '=kind',
  caption: '=name'
}

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

演示 Plunkr


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接