7

我应该能够将属性从 $scope 传递到这样的自定义指令中吗?

        <div ng-repeat="ratable in ratables">
            <div>How much do you like {{ratable.name}}?</div>

            <!-- CONFUSED - First element does not work, second element does -->
            <rating currentRatingValue="{{ratable.currentvalue}}" maxRatingValue="10"></rating>
        </div>

硬连线的“10”可以很好地传递到指令中,但是当我尝试传递 {{ratable.currentvalue}} 时的字符串插值似乎永远不会发生。我在做一些明显错误的事情吗?

http://jsfiddle.net/ADukg/2168/

var myApp = angular.module('myApp',[])
    .directive("rating", function () {
        return {
            restrict: "E",
            scope: {},
            template: "<div class='rating'>Current rating: {{currentratingvalue}} out of {{maxratingvalue}}</div>",
                link: function (scope, element, attributes) {
                    console.log(attributes.currentratingvalue);    // Does not work but seems like it should
                    console.log(attributes.maxratingvalue);        // Does work
                }
            };    
        });

function MyCtrl($scope) {
    $scope.name = 'Superhero';

    $scope.ratables = [
        { name: "sledding", currentvalue: 3, maxvalue: 5 },
        { name: "water skiing", currentvalue: 7, maxvalue: 10 },
        { name: "whitewater rafting", currentvalue: null, maxvalue: 10 }
    ];
}

<div>
    <div ng-controller="MyCtrl">
      Hello, {{name}}!

        <div ng-repeat="ratable in ratables">
            <div>How much do you like {{ratable.name}}?</div>

            <!-- CONFUSED - First element does not work, second element does -->
            <rating currentRatingValue="{{ratable.currentvalue}}" maxRatingValue="10"></rating>
        </div>
    </div>
</div>
4

1 回答 1

10

一些东西:

  • HTML中的指令属性需要使用kebab-case
  • 您不需要隔离范围(实际上它会导致问题);改为使用scope: true
  • 您需要设置本地范围属性,以便您的模板可以选择它们
  • $observe必须用于获取内插属性的值(即使用 {{}} 的属性)

HTML:

<rating current-rating-value="{{ratable.currentvalue}}" max-rating-value="10"></rating>

指示:

link: function (scope, element, attributes) {
   attributes.$observe('currentRatingValue', function(newValue) {
      console.log('newValue=',newValue);
      scope.currentRatingValue = newValue
   })
   scope.maxRatingValue = attributes.maxRatingValue;
   console.log('mrv=',attributes.maxRatingValue);
}

小提琴


这是一个使用隔离范围的版本:

.directive("rating", function () {
   return {
      restrict: "E",
      scope: { currentRatingValue: '@',
               maxRatingValue:     '@' },
      template: "<div class='rating'>Current rating: {{currentRatingValue}}"
              + " out of {{maxRatingValue}}</div>",
  };    
});

小提琴

如果您想在链接函数中查看隔离范围属性的值,则需要使用$observe$watch因为我们使用了“@”。如果使用 '=' (用于双向数据绑定),则不需要使用$observeor $watch

于 2013-03-26T19:55:00.633 回答