gpt4 book ai didi

javascript - AngularJS 嵌套组件和作用域

转载 作者:行者123 更新时间:2023-11-30 13:03:16 24 4
gpt4 key购买 nike

这是一个用于显示客户地址的组件(请原谅 Jade ):

address(style='{{addressStyle}}')
strong {{clinic.businessName}}
br
span {{clinic.address.address1}}
br
span(ng-switch='{{clinic.address.address2 != null}}')
span(ng-switch-when='true')
| {{clinic.address.address2}}
br
span {{clinic.address.suburb}} {{clinic.address.state}} {{clinic.address.postcode}}
br
abbr(title='Phone') P:
| {{functions.formatPhoneNo(clinic.phone)}}
app.directive('clinicAddress', function($interpolate) {
return {
restrict: 'E',
templateUrl: 'directives/clinicAddress',
scope: { clinic: '=', functions: '=' },
link: function(scope, element, attrs) {
scope.addressStyle = attrs.style ? scope.addressStyle = $interpolate(attrs.style)() : '';
}
};
});

还有一个基于它的,用于显示包裹在超链接中并带有 map 标记的客户地址:

a(href='#!/clinic/{{clinic.urlFragment}}')
div(style='width:50px;height:50px;background:url(/img/map/{{index+1}}.png) 190px 30px no-repeat;')
clinic-address(clinic='clinic', functions='functions', style='background:url(/img/map/{{index+1}}.png) 190px 30px no-repeat;')
app.directive('indexedClinicAddress', function() {
return {
restrict: 'E',
scope: { clinic: '=', index: '=', functions: '=' },
templateUrl: 'directives/indexedClinicAddress'
};
});

问题是,当 $interpolateclinicAddress 的指令中运行时,index 是未定义的,因为它在 indexedClinicAddress的范围。如何让 $interpolate 使用父作用域,我假设它与 indexedClinicAddress 作用域相同?

最佳答案

而不是使用 $scope.$parent 和 $interpolate 你应该使用范围 @ 属性 - 来自 the Angular directives guide :

@ or @attr - bind a local scope property to the value of DOM attribute. The result is always a string since DOM attributes are strings. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localName:'@myAttr' }, then widget scope property localName will reflect the interpolated value of hello {{name}}. As the name attribute changes so will the localName property on the widget scope. The name is read from the parent scope (not component scope).

app.directive('clinicAddress', function($interpolate) {
return {
restrict: 'E',
templateUrl: 'directives/clinicAddress',
scope: { clinic: '=', functions: '=', addressStyle:'@style' },
link: function(scope, element, attrs) {
}
};
});

关于javascript - AngularJS 嵌套组件和作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16625711/

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