Angular directive only repeats last element

I am trying to create a "tool" directive. I added three tools to my index.html, but instead of showing them all, I see the last one repeated three times: 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>
      

Run codeHide result


+3


source to share


1 answer


You have no scope in the directive, so the parent's scope is used. So you actually only have one scope.strain and scope.caption.

What you can do is add to the directive:

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

      



Remove the link function and use the upper case filter in the directive template.

Demo plunkr

+3


source







All Articles