我有一个div我在哪里渲染我的html字符串,我也有一个选项列表从控制器更新这个字符串,渲染html我使用ng-bind-html
和函数:
ng-bind-html="trustTemplate(data.emailNotification.textTemplate)"
$scope.trustTemplate = function (value) {
var trust = value.replace(/\{{/g, "<span class='label label-danger' contenteditable='false' style='padding: 6px; color: #FFFFFF; font-size: 16px;'>").replace(/\}}/g, "<span ng-click='click($event)' contenteditable='false' class='remove-tag fa fa-times'></span></span> ");
return $sce.trustAsHtml(trust);
};
这里的问题如果用户想要输入某些东西,那么ng-model不会更新它的值,我已经尝试$scope.$watch
或者从指令设置观察者,发现ng-model没有更新它的值,所以我相信双向绑定不起作用。
我的错误在哪里或我错过了什么?
完整代码:
HTML
<div id="template"
contenteditable="true"
style="height: 200px; width: 100%; border: 1px solid #d7d7d7; padding: 10px"
ng-model="data.emailNotification.textTemplate"
ng-bind-html="trustTemplate(data.emailNotification.textTemplate)"
markers
></div>
控制器
$scope.data.emailNotification.textTemplate = "User template user info: {{userFirstname}} - {{userLastname}}";
$scope.selectedVariables = function (item) {
if(item !== null){
$scope.data.emailNotification.textTemplate = $scope.data.emailNotification.textTemplate.concat(' {{' + item + '}} ');
}
};
$scope.trustTemplate = function (value) {
var trust = value.replace(/\{{/g, "<span class='label label-danger' contenteditable='false' style='padding: 6px; color: #FFFFFF; font-size: 16px;'>").replace(/\}}/g, "<span ng-click='click($event)' contenteditable='false' class='remove-tag fa fa-times'></span></span> ");
return $sce.trustAsHtml(trust);
};
$scope.$watch('data.emailNotification.textTemplate', function (newVal, oldVal) {
console.log(newVal);
console.log(oldVal);
//updates only with init and function selectedVariables (). Show actual value of $scope.data.emailNotification.textTemplate
});
$scope.selectedVariables(null);
指令
app.directive('markers', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$render = function () {
var newValue = ngModel.$viewValue;
console.log(newValue)
//updates only with init and function selectedVariables (). Show actual value of $scope.data.emailNotification.textTemplate
};
attrs.$observe('ngModel', function(value){ // Got ng-model bind path here
scope.$watch(value,function(newValue){ // Watch given path for changes
console.log(newValue);
//updates only with init and function selectedVariables (). Show actual value of $scope.data.emailNotification.textTemplate
});
});
}
}
});