gpt4 book ai didi

angularjs - 在自定义指令上设置属性值时,字符串插值不起作用

转载 作者:行者123 更新时间:2023-12-03 09:30:35 24 4
gpt4 key购买 nike

我应该能够将属性从 $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>

最佳答案

一些东西:

  • 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);
    }

    Fiddle

    这是一个使用隔离范围的版本:
    .directive("rating", function () {
    return {
    restrict: "E",
    scope: { currentRatingValue: '@',
    maxRatingValue: '@' },
    template: "<div class='rating'>Current rating: {{currentRatingValue}}"
    + " out of {{maxRatingValue}}</div>",
    };
    });

    Fiddle

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

    关于angularjs - 在自定义指令上设置属性值时,字符串插值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15645780/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com