[英]pass variable to angularjs directive template
我正在嘗試將變量傳遞給指令
app.directive('pagination',function () {
//custom directive for build pagination
return {
restrict: 'E'
template:function (elem,attr)
//not getting the value
console.log(attr.pageCount);
}
};
})
在我的HTML中
<pagination page-count="pageCount" ></pagination>
但是pageCount
值不在template
內部,而是page-count=2
這將為模板提供值
更新
<% var i = 1;
if (currentPage > 5) {
i = +currentPage - 4;
} %>
<% for (i; i<=pageCount; i++) { %>
<% if (currentPage == i) { %>
<li class="page-item active"><a href="#" class="page-link"><%= i %></a></li>
<% } else { %>
<li class="page-item"><a class="page-link" href="?page=<%= i %>"><%= i %></a></li>
<% } %>
<% if (i == (+currentPage + 4)) { %>
<% break; } %>
<% } %>
我想在angularjs中使用等效的HTML
可以從控制器獲取currentPage
和pageCount
值
再次更新
現在我可以獲取link
的值
return {
restrict: 'E',
scope: {
pagecount: '=',
currentpage: '='
},
template:function (elem,attr) {
return 'hello';
},
link:function (scope,elem,attr) {
console.log("count",scope.pagecount,scope.currentpage);
}
};
但是我該如何動態構建HTML
您可以通過兩種方式從范圍中檢索值。
使用scope: {}
隔離范圍,然后直接在頁面上使用該綁定。 您不能直接在template
函數中獲取作用域綁定。
app.directive('pagination',function ($compile) { //<- inject $compile //custom directive for build pagination return { restrict: 'E', template: '<div>{{pageCount}}</div>' scope: { pageCount: '='//or use `>` if it is Angular 1.5.3+ }, link: function (scope,elem) { //get scope.pageCount value and create template based on it. And append to body var template = 'myTemplateInStringFormat'; element.append($compile(template)(scope)); } }; })
從當前范圍評估價值。 在指令的鏈接函數中使用$eval
/ $parse
。 就像$scope.$eval('pageCount');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.