[英]pass variable to angularjs directive template
I am trying to pass variable to directive 我正在尝试将变量传递给指令
app.directive('pagination',function () {
//custom directive for build pagination
return {
restrict: 'E'
template:function (elem,attr)
//not getting the value
console.log(attr.pageCount);
}
};
})
in my html 在我的HTML中
<pagination page-count="pageCount" ></pagination>
but the pageCount
value is not getting inside the template
but page-count=2
this will give the value inside the template 但是
pageCount
值不在template
内部,而是page-count=2
这将为模板提供值
UPDATE 更新
<% 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; } %>
<% } %>
I want to equivalent HTML in angularjs 我想在angularjs中使用等效的HTML
currentPage
and pageCount
values can be get from the controller 可以从控制器获取
currentPage
和pageCount
值
UPDATE AGAIN 再次更新
Now i can able to get the values in link
现在我可以获取
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);
}
};
But how can i dynamically build the HTML 但是我该如何动态构建HTML
You could retrieve the value from the scope by couple of way. 您可以通过两种方式从范围中检索值。
Using scope: {}
isolated scope, and use that binding on page directly. 使用
scope: {}
隔离范围,然后直接在页面上使用该绑定。 You can't directly get scope bindings inside template
function. 您不能直接在
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)); } }; })
Evaluate value from the current scope. 从当前范围评估价值。 using
$eval
/ $parse
inside the link function of directive. 在指令的链接函数中使用
$eval
/ $parse
。 Like $scope.$eval('pageCount');
就像
$scope.$eval('pageCount');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.