下面是我的代码示例,在代码中我试图将DIV附加到标签。
我需要的是“DIV
tag之后我不需要label
元素”,但我需要在标签后附加一些html。
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular-sanitize.js"></script>
<script>
var app = angular.module('myApp', ['ngSanitize']);
app.controller('CartController', function($scope) {
$scope.title = "<b>Hello world</b>";
$scope.test = "How are you..!";
$scope.AppendText = function() {
var myEl = angular.element( document.querySelector('#divID'));
myEl.append('Hi<br/>How are U..?');
}
});
</script>
<body ng-app="myApp" >
<div ng-controller="CartController">
<label ng-bind-html="title" ng-init="AppendText()">
<div id="divID"></div>
</label>
</div>
</body>
</html>
答案 0 :(得分:1)
使用directives
可以更好地实现这一点。改变控制器中的DOM元素并不是一个好习惯。创建指令以在dom上进行操作。所有dom改变都应该使用指令。在侦探中,您可以轻松访问范围,元素和属性。在这里阅读更多https://docs.angularjs.org/guide/directive
我建议在下面的解决方案
var app = angular.module('myApp',[]);
app.controller('CartController', function($scope) {
$scope.title = "<b>Hello world</b>";
$scope.test = "How are you..!";
});
app.directive('appendText',function () {
return {
restrict: 'A',
link: function(scope, elm, attr) {
elm.html('Hi<br/>How are U..?');
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body ng-app="myApp" >
<div ng-controller="CartController">
<label> {{title}}
<div id="divID" append-text></div>
</label>
</div>
</body>