我正在我的页面上添加 html 文件的内容。充当需要在用户添加内容时更改的“预览”。为了争论,
<div>
{{introText}}
</div>
我正在使用 $http.get()
获取内容并使用 $sce.trustAsHtml()
在页面上插入 html。问题是 {{introText}}
未绑定(bind)到 Controller ,因此无法识别。
我有一个关于 ng-model="introText"
的输入,我想更新 {{introText}}
。
注意:我的 html 文件要长得多,但提供的 html 只是一个示例。
最佳答案
尝试使用$interpolate
:
(function(angular) {
'use strict';
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', '$interpolate', function($scope, $interpolate) {
$scope.introText = 'some text';
var templates = ['<div>{{introText}}</div>', '<h1>{{introText}}</h1>']
var i = 0;
$scope.inter = $interpolate(templates[i]);
$scope.template = function(){
i = 1 - i;
$scope.inter = $interpolate(templates[i]);
};
}]);
})(window.angular);
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="//code.angularjs.org/snapshot/angular-sanitize.js"></script>
<body ng-app="bindHtmlExample">
<div ng-controller="ExampleController">
<input type='text' ng-model='introText'/>
<input type='button' value='Change template' ng-click='template()'>
<p ng-bind-html="inter({introText})"></p>
</div>
</body>
关于javascript - 在 AngularJS 中,我可以添加一个也有 Angular 模板数据的 HTML block 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42195840/