Jquery append() 不与 angularjs 一起使用

Jquery append() not working with angularjs

本文关键字:一起 angularjs 不与 append Jquery      更新时间:2023-09-26

我们正在使用 jquery 1.9.1 和 angular 1.2.13。我们正在使用一个运行良好的所见即所得编辑器,我们将 html 保存到数据库中并使用 jquery 追加函数加载回 html 并且工作正常。现在我们尝试将相同的 html 附加到div 标签中(所见即所得编辑器也使用div),并且附加函数不起作用。我们在控制台中签入,我们尝试附加的字符串在那里,jquery 也抓取了元素(也在控制台日志中检查),但附加函数不起作用。

PD:我为我的英语道歉

目录

<div data-ng-controller="PreviewCtrl">
    <div class="container">
      <div id="resumenPreview"></div>                                
    </div>
</div>

控制器

angular.module('module').controller('PreviewCtrl', ['$scope', '$routeParams', '$location', '$http', 'selectedElement',
    function ($scope, $routeParams, $location, $http, selectedElement) {
        $scope.id = $routeParams.id;
        $scope.mensaje = $scope.id;        
        $scope.imagen = null;
        $scope.dataImagen = null;
        //is not working either
        $('#resumenPreview').append("hola");   
        $scope.pageLoad = function () {            
            var x = selectedElement.data.Resumen;
            //This is properly displayed in the console
            console.log(x);
            //This too, is displayed in the console log
            console.log($('#resumenPreview'));
            // Why this isn't working? I'am clueless
            $('#resumenPreview').append(x);
        };
        $scope.pageLoad();
    }]);

我的猜测是有多个div 的 id="resumenPreview"。但这显然是用角度处理这些事情的错误方式。控制器中不应该有 dom 操作 - 指令应该处理与 dom 相关的东西。将 html 字符串放入作用域中,让 angular 处理注入到 dom 中:

而不是$('#resumenPreview').append(x);$scope.resumenPreview = x;

并在模板中执行此操作:

<div class="container">
      <div ng-bind-html="resumenPreview"></div>                                
</div>

用angularjs解决它,以便ng-bind-html工作,有必要包含

 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular-sanitize.js"></script>

并在应用程序模块配置中添加"ngSanitize"作为依赖项。然后按照路透社发布@Johannes去做。谢谢大家,问候。