Question

Question Link Plnkr

http://plnkr.co/edit/iWTkPrDDvrDdc4LRQjTN?p=preview

code is like:

<!doctype html>
<html ng-app="docsSimpleDirective">
<head>
  <script src="http://code.angularjs.org/1.2.6/angular.min.js"></script>
</head>
<body>
  <div ng-controller="Ctrl">
    <div ng-repeat="line in lines">
      <div ng-repeat="action in actions" format>{{action.content}}</div>
    </div>
  </div>
  <script>
    angular.module('docsSimpleDirective', [])
      .controller('Ctrl', function($scope) {
        $scope.lines = [
          ['11', '12', '13'],
          ['21', '22', '23'],
          ['31', '32', '33']
        ];
        $scope.actions = [{
          content: '{0}'
        }, {
          content: '{2}'
        }];
      })
      .directive('format', function() {
        return function(scope, elm, attrs) {
          scope.action.content = scope.action.content.replace(/\{\d+\}/g, function(number) {
            return scope.line[number.slice(1, -1)];
          });
          //scope.action.content = 1;
        };
      });
  </script>
</body>
</html>

but why the result is: 11 13 11 13 11 13

I expect it is 11 13 21 23 31 33

why the line not change?

Was it helpful?

Solution 2

Formatting is the job of a filter, not directive. Try:

<div ng-controller="Ctrl">
    <div ng-repeat="line in lines">
      <div ng-repeat="action in actions">{{line | format:action.content }}</div> //Change this line to use filter to format output
    </div>
  </div>
  <script>
    angular.module('docsSimpleDirective', [])
      .controller('Ctrl', function($scope) {
        $scope.lines = [
          ['11', '12', '13'],
          ['21', '22', '23'],
          ['31', '32', '33']
        ];
        $scope.actions = [{
          content: '{0}'
        }, {
          content: '{2}'
        }];
      })
      .filter('format', function() { //Create a filter
        return function(line,content) {
          return content.replace(/\{\d+\}/g, function(number) {
            return line[number.slice(1, -1)];
          });
          //scope.action.content = 1;
        };
      });
  </script>

DEMO

OTHER TIPS

<div ng-controller="Ctrl">
    <div ng-repeat="line in lines">
    {{line[0]}} {{line[2]}}
      <!-- <div ng-repeat="action in line" format>{{action}}</div> -->
    </div>
  </div>

I think for your case you don't even need the actions. Just do it like this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top