我的自定义指令运行良好的onload页面加载但是当使用append添加时它无法正常运行。它在运行时没有显示其内容。
HTML:
<!doctype html>
<html lang="en" ng-app="module1">
<head>
<meta charset="UTF-8">
<title>Angular Demo</title>
<link rel="stylesheet" href="css/bootstrap.css">
<script src="js/angular.js"></script>
<script src="js/ui-bootstrap-tpls-0.13.0.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<div id="divContainer" style="border-style: solid;border-color:red;" ng-controller = "Controller1 as cnt1" >
<button ng-click="clicked();">Click Me!!</button>
<wlaccordion></wlaccordion>
</div>
</body>
</html>
app.js:
var app = angular.module('module1',[]);
app.controller('Controller1', ['$scope', function($scope) {
$scope.authorData = authorInfo;
$scope.clicked = function () {
alert('Clicked');
//angular.element(document.getElementById('divContainer')).append('<wlaccordion1></wlaccordion1>' (scope));
angular.element(document.getElementById('divContainer')).append('<wlaccordion></wlaccordion>');
}
}]);//controller1
var authorInfo = [
{
'name': 'Ray',
'rate': '10',
'show': 'true'
},
{
'name': 'Mahesh',
'rate': '12',
'show': 'true'
}
]
app.directive("wlaccordion", function($compile) {
var template = '<div ng-controller = "Controller1 as cnt1">' +
'<div ng-repeat="aData in authorData" ng-init="tab = 1">' +
'<ul>' +
'<li>' +
'<h1 ng-show={{aData.show}} ng-class="{active: tab === 1}"> {{aData.name}} </h1>' +
'<h1 ng-show={{aData.show}} ng-class="{active: tab === 2}"> {{aData.rate | currency}} </h1>' +
'</li>' +
'</ul>' +
'</div>' +
'</div>';
return{
link: function(scope, element){
var content = $compile(template)(scope);
element.append(content);
}
}
});
我希望该指令的功能与onload相同。
-Thanks 马赫什
答案 0 :(得分:1)
AngularJS旨在分离表示逻辑和业务逻辑。所以我认为你应该以Angular方式做到这一点,你当前的方法更多是jQuery之一。
我建议你将accordions collection添加到控制器:
app.controller('Controller1', ['$scope', function($scope) {
$scope.accordions = [0]; // Replace 0 with some actual data
$scope.clicked = function() {
$scope.accordions.push($scope.accordions.length); // Same here
};
// Your other code
}
在HTML中添加ng-repeat
:
<div id="divContainer" style="border-style: solid;border-color:red;" ng-controller = "Controller1 as cnt1" >
<button ng-click="clicked();">Click Me!!</button>
<wlaccordion ng-repeat="accordion in accordions"></wlaccordion>
</div>
修改:另请不要忘记从wlaccordion
的{{1}}删除编译。
编辑#2:我认为link
全局变量仅用于举例,但如果没有,则考虑使用authorInfo
或{{1} }
答案 1 :(得分:0)
app.controller('Controller1', ['$scope','$compile', function($scope, $compile) {
$scope.authorData = authorInfo;
$scope.clicked = function () {
alert('Clicked');
//angular.element(document.getElementById('divContainer')).append('<wlaccordion1></wlaccordion1>' (scope));
angular.element(document.getElementById('divContainer')).append($compile('<wlaccordion></wlaccordion>')($scope));
}
}]);//controller1