Я хочу написать HTML-код внутри DIV после получения данных из службы, но он не работает. Это мои html
и js
коды. Как я могу исправить?
Благодарю.
index.html:
<html>
<head>
<title>AngularJS</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-sanitize.js"></script>
<script src=script></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<div ng-bind-html="htmlcode">
</div>
</div>
</body>
</html>
script.js:
(function(angular) {
'use strict';
angular.module('myApp', ['ngSanitize'])
.controller('myController', ['$window', '$scope', '$http', function($window, $scope, $http) {
html = "<ul><li>Item-1<ul><li>SubItem-1</li></ul></li><li>Item-2</li></ul>";
$scope.htmlcode= html;
var res = $http.post(service_url);
res.success(function(result, status, headers, config) {
});
}]);
})(window.angular);
script1.js:
(function(angular) {
'use strict';
angular.module('myApp', ['ngSanitize'])
.controller('myController', ['$window', '$scope', '$http', function($window, $scope, $http) {
var res = $http.post(service_url);
res.success(function(result, status, headers, config) {
html = "<ul><li>Item-1<ul><li>SubItem-1</li></ul></li><li>Item-2</li></ul>";
$scope.htmlcode= html;
});
}]);
})(window.angular);
РЕЗУЛЬТАТ (script1.js):
SubItem-1
не отображается как подпункт Item-1
РЕЗУЛЬТАТ (script.js):
Не манипулируйте html внутри контроллера, используя для этого диалекты или службы. Это нужно делать с помощью ng-repeat.
(function(angular) {
'use strict';
angular.module('myApp', ['ngSanitize'])
.controller('myController', ['$window', '$scope', '$http', function($window, $scope, $http) {
$scope.items = [];
var res = $http.post(service_url);
res.success(function(result, status, headers, config) {
$scope.items.concat(result.items);
});
}]);
})(window.angular);
//шаблон
<body ng-app="myApp">
<div ng-controller="myController">
<ul class="items">
<li ng-repeat="item in items">
{{item.name}}
<ul class="sub-items">
<li ng-repeat="subitem in item.subItems">{{subitem.name}}</li>
</ul>
</li>
</ul>
</div>
</body>
//items.json
{
"items": [
{
"name": "item1",
"subItems": [
"name": "subItem1"
]
}
]
}