[英]src stripped from json html data when using angular.js and angular-sanitize.js
[英]Select option values returns null when using binding html from JSON in Angular.js
我使用自定义指令将存储为JSON的HTML表单动态绑定到视图模板中。
该HTML包含一个选择标记和使用ng-repeat动态生成的选项,以及使用ng-model设置谁的模型。
问题是来自select标签的绑定数据返回为null
这是整个Model-View-Controller设置:
带有HTML的JSON:
{"location":"<input class='form-control' type='text' placeholder='City' ng-model='model.location.city'/><select class='form-control' ng-model='model.location.state'><option value=''>State</option><option ng-repeat='(k, val) in states' value='{{k}}'>{{val}}</option></select>"}
..解决此问题:
<input class='form-control' type='text' placeholder='City' ng-model='model.location.city'/>
<select class='form-control' ng-model='model.location.state'>
<option value=''>State</option>
<option ng-repeat='(k, val) in states' value='{{k}}'>{{val}}</option>
</select>
查看模板:
<div bind-html-compile="html_from_json">
<!-- to be filled with HTML from JSON file -->
</div>
<button ng-click="getdata()">get form data</button>
指令进行绑定:
.directive('bindHtmlCompile', ['$compile', function ($compile) {
return {
restrict: 'AE',
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.bindHtmlCompile);
}, function (value) {
element.html(value && value.toString());
var compileScope = scope;
if (attrs.bindHtmlScope) {
compileScope = scope.$eval(attrs.bindHtmlScope);
}
$compile(element.contents())(compileScope);
});
}
};
}]);
控制器与模型
.controller('testCtrl', function($scope, $http, $state, $sce){
$scope.model = {
location : {
city:'', // this works fine!
state:'' // this comes back as null
}
};
$http.get('html_form.json').then(function(res){
$scope.html_from_json = $sce.trustAsHtml(res.data['location']);
$scope.getdata = function(){
console.log($scope.model);
};
});
});
当在“城市”字段中输入“纽约”并选择给定状态时,这是日志的输出:
如果我将HTML表单直接放入视图(而不是从JSON中提取),则一切正常。 似乎是从JSON字符串获取数据是导致此问题的原因。
更奇怪的是,以下内容:
console.log($scope.model.location);
确实会返回选定状态,但是在开发控制台中扩展对象或尝试使用数据会解析为null。
有谁知道这可能是什么原因以及如何解决?
-更新-
我发现可以通过将JSON html的ng-models设置为非对象值来解决此问题。 例如:
<select ng-model="state"></select> <!-- this works -->
与
<select ng-model="location.state"></select> <!-- this returns null -->
然后,我将值反馈回控制器中的模型:
$scope.model.location.state = $scope.state;
但这有点粗糙。 我仍然想知道问题所在。
在下面使用此代码,在select选项中使用ng-repeat并不是一个好习惯,因为存在ng-options。
<select class='form-control' ng-model='model.location.state' ng-options='k as val for (k, val) in states'>
</select>
可能对您有帮助,祝您好运:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.