2013-05-18 49 views
1

下面是显示客户的地址组件(请原谅Jade):AngularJS嵌套组件和范围

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

回答

3

而不是使用$范围$家长和$插你应该应该使用范围@属性 - 从the Angular directives guide

@或@attr - 将本地范围属性绑定到DOM属性的值。结果总是一个字符串,因为DOM属性是字符串。如果未指定attr名称,则假定属性名称与本地名称相同。给定范围的小部件定义:{localName:'@ myAttr'},那么小部件范围属性localName将反映hello {{name}}的内插值。由于名称属性发生变化,widget属性的localName属性也会发生变化。该名称是从父作用域(不是组件作用域)读取的。

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

谢谢!它的工作,这很简单,我学到了一些东西。 –

+0

有趣的是,当浏览器尝试获取样式中未插入的资源时,我仍然收到404。我认为这一直在抛我。现在我仍然看到它,我认为这只是浏览器做的事情,因为这个属性被称为'style'。 –

+1

理论证实。现在使用'elementStyle'而不是'style'来防止向服务器发送不必要的请求,否则将以'404'响应。 –

0

使用

$scope.$parent 

得到父作用域参考