0

Imagine a scope variable which is read and does change: total_number. I want to build an equal number of divs if total_number<=10 or the half amount if 10< total_number<=20. I guess I have to use a directive, however I do not know how to define the different number of divs...May I use link and what do I have to write?

1 Answer 1

1

Made an example by directive , hope it works for you. Any questions let me know plz.

angular.module('app', [])
  .controller('appCtrl', function($scope, $filter) {
    $scope.total_number = 10;
  })
  .directive('divBuilder', function() {
    return {
      restrict: 'EA',
      scope: {
        count: '@'
      },
      link: function(scope, element, attrs) {
        var count = Number(scope.count);
        if (!count || count <= 0) {
          return false;
        }
        if (count > 10 && count <= 20) {
          count = Math.floor(count / 2);
        }
        var div = '';
        for (var i = 0; i < count; i++) {
          div += '<div class="line">' + (i + 1) + '</div>';
        }

        element.append(div);
      }
    };
  });
div.line {
  border: 1px solid #ccc;
  margin: 10px 0;
  padding: 2px 10px;
}
<html>

<head>
  <title>Single Demo</title>
  <script src="//cdn.bootcss.com/jquery/2.2.1/jquery.js"></script>
  <script src="//cdn.bootcss.com/angular.js/1.4.7/angular.js"></script>
  <script src="app.js"></script>

</head>

<body ng-app="app" ng-controller="appCtrl">
  <div-builder count="{{total_number}}"></div-builder>
</body>

</html>

Sign up to request clarification or add additional context in comments.

1 Comment

Adding some commentary to your solution (how it works / what it does) would be a good idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.