Angular 1.4解析ng-bind-html的内容

Angular 1.4 parse contents of ng-bind-html

本文关键字:ng-bind-html 解析 Angular      更新时间:2023-09-26

我在做什么?

简单地说:我有一个名为$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