AngularJS嵌套组件和范围

时间:2013-05-18 15:05:17

标签: javascript angularjs

这是显示客户地址的组件(请原谅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)() : '';
        }
    };
});

另一个基于它,用于显示包含在超链接中的客户地址和地图标记:

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的范围相同?

2 个答案:

答案 0 :(得分:3)

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

  

@或@attr - 将本地范围属性绑定到DOM属性的值。结果总是一个字符串,因为DOM属性是字符串。如果未指定attr名称,则假定属性名称与本地名称相同。范围的给定和窗口小部件定义:{localName:'@ myAttr'},然后窗口小部件范围属性localName将反映hello {{name}}的内插值。随着name属性的更改,widget命名空间上的localName属性也会更改。从父作用域(而不是组件作用域)读取名称。

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

答案 1 :(得分:0)

使用

$scope.$parent

获取对父作用域的引用