在自定义指令上设置属性值时,字符串插值无效

bla*_*ter 7 angularjs

我是否应该能够将$ 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>
Run Code Online (Sandbox Code Playgroud)

硬连线的"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>
Run Code Online (Sandbox Code Playgroud)

Mar*_*cok 10

一些东西:

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

HTML:

<rating current-rating-value="{{ratable.currentvalue}}" max-rating-value="10"></rating>
Run Code Online (Sandbox Code Playgroud)

指示:

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);
}
Run Code Online (Sandbox Code Playgroud)

小提琴


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

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

小提琴

如果要在链接函数中查看isolate scope属性的值,则需要使用$observe$watch因为我们使用了'@'.如果使用'='(对于双向数据绑定),则不需要使用$observe$watch.

  • 如果上述任何一点不清楚,肯定会问.Angular有一个相当陡峭的学习曲线. (3认同)