2016-09-28 166 views
0
<tab page="book"> </tab> 
    <tab page="dial"> </tab> 
    <tab page="groupe"> </tab> 
    <tab page="log"> </tab> 
    <tab page="star"> </tab> 

正如你可以看到我有一個名爲標籤指令,這標籤有一個屬性角指令範圍值

我需要根據改變templateUrl頁面屬性

如果page="abc"那麼templateUrl應該templateUrl: 'tab/abc.html',

這裏是我的指令代碼

contactBook.directive('tab', function() { 
    let m = 'tab/default.html'; 
    return { 
     restrict: 'E', 
     scope: { 
      page: '@', 
     }, 
     templateUrl: m, 
     link: function(scope, element, attributes) { 
      m = "tab/" + scope.page + ".html";  
     }, 
    }; 
}); 

這是邏輯上可能..?或任何其他方法來做到這一點..?

+0

與頁嘗試:「=」而不是頁面:「@」,這將讓您可以立即使用內部鏈接的屬性值。 –

回答

7
templateUrl: function(elem,attrs) { 
    return "tab/" + attrs.page + ".html" || 'tab/default.html'; 
}, 
+0

感謝它解決了我的問題,但我不知道varibale elem,attrs來自哪裏, – Sajan

+0

元素是調用指令的地方,屬性是與該元素關聯的對象。作爲參考,您也可以查看https://docs.angularjs.org/guide/directive –

2
contactBook.directive('tab', function() { 
    let m = 'tab/default.html'; 
    return { 
     restrict: 'E', 
     scope: { 
      page: '@', 
     }, 
     templateUrl: m, 
     link: function(element, attributes) { 
      m = "tab/" + attributes.page + ".html"; // attributes.page can access attribute value 
     }, 
    }; 
}); 

要隔離的標籤指令範圍和已綁定

scope: { 
      page: '@', 
    } 

如果你只是一個string傳遞父範圍的指令,然後使用

<tab page={{book}}> </tab> 

但是如果你想從父範圍傳遞一個對象到指令,那麼

<tab page="book"> </tab> 

然後在指令

scope: { 
       page: '=', 
     }