gpt4 book ai didi

angularjs - 用@ 定义的隔离作用域属性在指令的链接函数中未定义/消失

转载 作者:行者123 更新时间:2023-12-04 17:23:42 24 4
gpt4 key购买 nike

该指令具有隔离作用域,作用域属性通过“@”传递。

这就是指令的调用方式:

<div ng-init="classForIcon = 'vladClass'"></div>
<div ng-init="textForIcon = 'Icon\'s text'"></div>
<div ng-init="routeForIcon = 'www.google.com'"></div>
<div ng-init="tooltipForIcon = 'my tooltip'"></div>
<div ng-init="imageForIcon = 'images/HOME_ICON1.png'"></div>

<rl-icon-widget icon-class="{{classForIcon}}" icon-text = "{{textForIcon}}" icon-tooltip="{{tooltipForIcon}}" icon-route="{{routeForIcon}}" icon-image="{{imageForIcon}}"></rl-icon-widget>

这是指令的定义方式:

'使用严格';
fcPortalApp.directive('rlIconWidget', ['localizationAssistant', function(localizationAssistant) {
var obj = {
restrict: 'E',
templateUrl: 'scripts/directives/rliconwidget/rliconwidget.html',

//require: 'ngModel',
scope: {
//ngModel: '@',
iconClass: "@",
iconRoute: "@",
iconText: "@",
iconTooltip: "@",
iconImage: "@"
},

link: function(scope, element, attrs) {

console.log(scope);
console.log(scope.iconImage);
console.log(scope.iconTooltip);
console.log(scope.iconRoute);

}
};

console.log(obj);
return obj;

}]);

当我检查范围对象(单击 console.log(scope_ in firebug) 的输出时,它看起来好像正确设置了 iconImage、iconTooltip 和 iconRoute 属性。

然而 console.log(scope.iconImage), console.log(scope.iconTooltip) 和 console.log(scope.iconRoute) 打印“未定义”

最佳答案

Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined. -- directive doc



当您手动检查范围时,值已定义。

我们需要使用 $observe(实际上 $watch 也适用于用“@”定义的隔离作用域属性)的原因是因为每当插入值发生变化时,指令可能需要做一些事情。例如,如果 textForIcon 的值更改,您可能希望修改由您的指令管理的 DOM 中的某些内容。

如果您需要在链接函数运行时定义的值,您有两个选择:
  • 使用“=”代替“@”。这将要求您从 HTML 中删除 {{}}。
  • 如果值不会改变,传递字符串:<rl-icon-widget icon-class="vladClass" ...>然后在您的指令中,只需使用 attrs.iconClass -- 不需要'@'。
  • 关于angularjs - 用@ 定义的隔离作用域属性在指令的链接函数中未定义/消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15253471/

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