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

标签 angularjs

我正在尝试创建一个“工具”指令。我在 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/

相关文章:

angularjs - 如何防止 anchor 标签默认?

javascript - 在输入文本中书写时保持专注于下拉列表

javascript - 尝试连接 angularJS $http 时出现 mongodb 服务器错误

javascript - 在 Angular JS 中使用条件 ng-class 时遇到问题?

php - angularjs路由,如何检查模板文件是否存在

angularjs - 如何从禁用按钮中删除工具提示?

javascript - html <object> 标签中的angularjs表达式

javascript - 为什么我应该在单元测试中模拟 HTTP 请求?

javascript - 无法让 Angular 自定义过滤器工作

javascript - 单元测试中卡住的 promise