gpt4 book ai didi

javascript - 如何将 html 代码与 ng-... 属性绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 04:22:23 24 4
gpt4 key购买 nike

我想创建<select ng-model='selected' ng-options='stage as stage.name for stage in stages'></select>变量中的元素作为字符串。正如您在此处看到的,select 元素中有 ng-... 属性。如果我使用不带 ng-... 属性的 select 元素,它的显示不会有问题。如果我在其中使用 ng-...,它不会显示任何内容。那么,如何让它显示为 ng-... ?请帮忙。

我的html代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-sanitize.js"></script>
<script src="Scripts/myScripts/index.js"></script>
</head>
<body>
<div ng-app="myapp" ng-controller="myCtrl">
<div ng-bind-html="htmlCode">
</div>
</div>
</body>
</html>

我的js代码:

var app = angular.module('myapp', ['ngSanitize']);

app.controller('myCtrl', ["$scope", function ($scope) {

$scope.stages =
[{ name: "Identification of Discontinuing Factors", value: 1 },
{ name: "Project Level Assessment", value: 2 },
{ name: "Organizational Readiness Assessment", value: 3 }];

$scope.htmlCode = "<select ng-model='selectedStage' ng-options='stage as stage.name for stage in stages'></select>";
}]);

最佳答案

您需要重新编译 dom 才能使用 ng- 属性。将此指令用作 ng-bind-html 元素的属性。

.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});

演示

var app = angular.module('myapp', []);

app.controller('myCtrl', ["$scope","$sce", function ($scope,$sce) {

$scope.stages =
[{ name: "Identification of Discontinuing Factors", value: 1 },
{ name: "Project Level Assessment", value: 2 },
{ name: "Organizational Readiness Assessment", value: 3 }];

$scope.htmlCode = "<select ng-model='selectedStage' ng-options='stage as stage.name for stage in stages'></select>";

$scope.trust = function(html){
return $sce.trustAsHtml(html)
}
}]);

app.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="myCtrl">
<div ng-bind-html="trust(htmlCode)" dynamic>
</div>

{{selectedStage}}
</div>

关于javascript - 如何将 html 代码与 ng-... 属性绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43888116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com