2014-02-15 44 views
0

如果有指令定義,那麼通過定義在其上的屬性傳遞給它的範圍可以在此指令中使用,以獲得模板中使用的所需結果?即我有這樣的指令可以在指令內使用指令隔離範圍進行計算

var carAuction = angular.module('carAuction'); 

carAuction 
    .controller('mainCtrl', function($scope) 
    { 
     var car = { 
      comments: [] 
     }; 

     car.comments.push({ 
      comment: 'Ok car', 
      rating: 1 
     }); 

     car.comments.push({ 
      comment: 'Nice car.', 
      rating: 2 
     }); 

     car.comments.push({ 
      comment: 'Awesome car!', 
      rating: 3 
     }); 

     $scope.car = car; 
    }) 
    .directive('carCommentRaiting', function() 
    { 
     return 
     { 
      restrict: 'E', 
      templateUrl: 'path/to/template.html', 
      scope: 
      { 
       value: '=value', 
       maxValue: '=max-value' 
      } 
     }; 
    }) 
    .filter('range', function() 
    { 
     return function(input, total) 
     { 
      total = parseInt(total); 

      for (var i=1; i<=total; i++) 
      { 
       input.push(i); 
      } 

      return input; 
     }; 
    }); 

在HTML部分我有

<div> 
    <div ng-repeat="comment in car.comments"> 
     Rating: <car-comment-raiting value="comment.rating" max-value="10"></car-comment-raiting> 
    </div> 
</div> 

template.html

<div> 
    <ul class="list-inline"> 
     <li ng-repeat="n in [] | range:value"><span class="glyphicon glyphicon-star"></span></li> 
    </ul> 
</div> 

而且我想通過額外的價值模板,應計算爲maxValue - value。還沒有找到任何描述這個的例子。想到使用link屬性,但是描述告訴,它被用於其他目的。

UPD: 我能夠與

return { 
    restrict: 'E', 
    templateUrl: 'path/to/template.html', 
    scope: 
    { 
     value: '=', 
     maxValue: '=' 
    }, 
    controller: function($scope) 
    { 
     $scope.calculated = $scope.maxValue - $scope.value; 
    } 
}; 

修復它,但由於某種原因,它不工作的所有時間。有一次它有效,另一次是calculated變量是null

+0

請郵寄'template.html'或小提琴 –

回答

2

所有計算必須在直接鏈接功能或控制器內完成。 這裏是例如與指令:

.directive('carCommentRaiting', function() { 
     return { 
      restrict: 'E', 
      template: 'path/to/template.html', 
      scope: { 
       value: '=value', 
       maxValue: '=max-value' 
      }, 
      link : function(scope, element, attr) { 
       scope.calculated = scope.maxValue - scope.value; 
       /// watch value to update calculated on value update: 
       scope.$watch('value', function(newValue){ 
         scope.calculated = scope.maxValue - newValue; 
       }); 
      } 
     }; 
    }); 
+0

試圖在控制,但並沒有解決這個問題,但鏈接財產是我一直在尋找的魔力。也沒有必要計算外部'$ watch'。謝謝。 – Eugene