2013-05-18 45 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 

得到父作用域參考