Angular 1.4解析ng-bind-html的内容
Angular 1.4 parse contents of ng-bind-html
我在做什么?
简单地说:我有一个名为$scope.myData的对象数组和一个名为主$scope.layout的字符串。我想做的是有一个包含ng-repeat="x in myData"
和ng-bind-html="layout"
的跨度。布局在几个位置具有{{ x.key }}
。我希望它加载布局,然后开始为数组中的每个对象显示布局,并填充变量。
更具体地说:我通过AJAX(使用jQuery)加载数据和布局。我不确定这是否重要,因为其他一切都很好。
到目前为止我有什么代码
我在$scope.layout
变量中包含angular-sance.js来取消初始化我的HTML。我还在app=angular.module()
声明中添加了ngSanitize
。
在AJAX方面,您实际上只需要阅读if(status=='success'){}
中的内容,因为该部分是有效的。
<script type="text/javascript">
$(document).ready(function(){
$('a.doit').click(function(e){
e.preventDefault();
$.ajax({
method:'POST',
data:{'ajax':true},
url:'<?=URL('--url to load from--')?>'
}).always(function(data,status){
if(status=='success'){
var getelementby='[ng-app="myApp"]';
window.data=data;
angular.element(document.querySelector(getelementby)).scope().$apply(function($scope){
$scope.layout=window.data.layout;
$scope.myData=window.data.data;
});
}else{
console.log('Error :(');
}
});
});
});
var app=angular.module('myApp',['ngSanitize']);
app.controller('myCtrl',function($scope,$http){$scope.myData={};});
</script>
<a href="#" class="doit btn btn-default">Load</a>
<div ng-app="myApp" ng-controller="myCtrl">
<span ng-repeat="x in myData"><span ng-bind-html="layout"></span></span>
</div>
(我知道到目前为止我的错误检查很粗糙)
它做什么它显示布局正确的次数,但不填充{{ x.key }}
表达式。
我可能做错了什么?我已经取消初始化我的HTML了。这不是棱角分明的工作方式吗?还有别的办法吗?
您不应该通过ng-bind-html加载角度模板。
取而代之的是:
// controller
$scope.templ = '{{ x }}';
// template
<div ng-bind-html="templ"></div>
将模板移动到其自己的指令:
// someDirective.js
angular.module('my.module').directive('myTemplate', function () {
return {
template: '{{ x }}'
};
});
并在您的原始模板中使用该指令:
<some-directive />
您需要使用控制器中的函数来执行与使用jQuery相同的操作。以下是一些应该有效的代码。
app.controller('myCtrl',['$scope', '$http', function($scope,$http){
$scope.myData={};
$scope.getAjaxData = function(){
$http({
method: 'POST',
data:{'ajax':true},
url: '/someUrl'
}).then(function successCallback(response) {
$scope.myData = response.data;
}, function errorCallback(response) {
console.log('error');
});
}
}]);
然后在HTML中尝试使用以下内容显示数据。。。
<a ng-click="getAjaxData()" class="doit btn btn-default">Load</a>
<span ng-repeat="x in myData">
<p ng-bind="x.key"></p>
<p ng-bind="x.value"></p>
</span>
这只是一个粗略的例子。试试看是否有效。
谢谢,Paras
相关文章:
- 显示&作为&在jsp中使用angularjs而不使用ng-bind-html
- Angular 1.4解析ng-bind-html的内容
- ng-bind-html 工作,但抛出错误
- AngularJS: ng-bind-html remove styling
- 为什么我的指令是't使用ng-bind-html指令
- ng-bind-html在点击锚标记或ng-click之前不显示
- angular ng show/ng hide无法正确使用ng bind html
- ng-bind-html中的angular命令
- Angular ng-bind-html - 阻止执行JS代码
- 如何使ng-bind-html编译angularjs代码
- Angularjs 和 ng-bind-html 无法正常工作
- Angularjs selectbox 在使用 ng-bind-html 时不反映底层 ng-model
- AngularJS指令:具有范围值的模板(ng-bind-html)
- 在ng-bind-html中呈现角度代码
- ng-bind-html 添加拥有 CSS 类“ng-binding”,它破坏了所有嵌套的 css,如何摆脱它
- Combining ng-repeat and ng-bind-html?
- AngularJS ng-bind-html
- Angular:将 transclude 与 ng-bind-html 结合使用
- 为什么AngularJS在使用ng-bind-html时会去除数据属性
- ng-bind-html无法解析正确的HTML并绑定它