【发布时间】:2015-05-29 13:41:39
【问题描述】:
我的自定义指令在加载页面加载时运行良好,但使用附加添加时它无法正常运行。它在运行时不显示其内容。
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 相同。
-谢谢 马赫什
【问题讨论】:
-
.append是一件非常非 Angular 的事情。你应该使用ng-if来切换你的手风琴 -
@RGraham 我将获得 JSON 格式的新数据,基于这些数据我需要重建视图。现在我刚刚放了静态数据。
-
为什么要编译
link函数中的代码而不是使用指令的模板属性? -
我尝试了各种组合,没有一个有效,即使这个在添加元素时也不起作用。我只需要一种方法来使用元素 append 显示
指令,因为它在文档加载时显示。 -
你不能只附加一个指令。它需要被编译(查看 $compile:code.angularjs.org/1.3.14/docs/api/ng/service/$compile)。也就是说,@RGraham 是正确的。不要在你的控制器中操作 DOM !!! code.angularjs.org/1.3.14/docs/guide/controller。使用内置指令,例如 ng-include 或 ng-if,或创建自己的指令。
标签: javascript angularjs