jquery方法不是从angular回调调用的

jquery method is not calling from angular callback?

本文关键字:回调 调用 angular 方法 jquery      更新时间:2023-09-26

我有以下代码:

$http({method: 'GET', url: 'api/participants/areyouhuman'})
            .success(function(data, status, headers, config) {
                console.log(data);
                $('.result').html(data);
                //$('.result').append('<p>Test</p>');
        })
        .error(function(data, status, headers, config) {
            console.log('error');
        });

data具有以下特性:

'<div id="AYAH">mk</div><script src="https://ws.areyouahuman.com/ws/script/8e53b417da61504de194550d3a6bf05c65d2a2b1" type="text/javascript" language="JavaScript"></script>'

当成功时,回调执行视图不反映为新的html。

我有以下html代码:

     <div class="form-group">
            <div class='result'></div>
     </div>

你能告诉我哪里做错了吗。或者任何其他方法(如果有的话)?

  1. 使用AngularJS时,为什么要使用jQuery
  2. jQuery加载了吗
  3. 此代码适用于我:http://jsfiddle.net/Schniz/j7p2zxrs/
  4. 我建议您更改$scope,而不是自己控制DOM。那是angular的工作

您需要更改两件事。

  1. 不要在控制器中操作DOM元素(这是一种糟糕的做法),而是使用普通的Angular数据绑定:

    $http({method: 'GET', url: 'api/participants/areyouhuman'})
      .success(function(data, status, headers, config) {
        console.log(data);
        $scope.htmlData = data;
    })
    .error(function(data, status, headers, config) {
        console.log('error');
    });
    
  2. 为了呈现外部HTML内容,您需要使用ng-bind-html指令:

    <div class="form-group">
      <div class='result' ng-bind-html="htmlData"></div>
    </div>
    

如果您得到一个$sce:ansafe错误,您将不得不告诉Angular使用$sce服务"信任"该HTML,如下所示:

$http({method: 'GET', url: 'api/participants/areyouhuman'})
    .success(function(data, status, headers, config) {
        console.log(data);
        $scope.htmlData = $sce.trustAsHtml(data);
        ...

(别忘了添加$sce作为控制器的依赖项)

用以下代码段更新:

$http({method: 'GET', url: 'api/participants/areyouhuman'})
        .success(function(data, status, headers, config) {
            console.log(data);
            $scope.content = data;
            //$('.result').html(data);
            //$('.result').append('<p>Test</p>');
    })
    .error(function(data, status, headers, config) {
        console.log('error');
    });

HTML:

<div class="form-group">
        <div class='result'>{{content}}</div>
</div>

这里的第一件事是,您不应该像在Angularjs中那样进行DOM操作。由于Angular有一个强大的双向绑定,所以你的代码会像这个一样

// I assume you're calling an ajax request in a controller
$http({method: 'GET', url: 'api/participants/areyouhuman'})
        .success(function(data, status, headers, config) {
            // Have a scope variable within the same scope will help you 
            $scope.dataAjax = data;
    })
    .error(function(data, status, headers, config) {
        console.log('error');
    });

然后在你的HTML中,你可能需要这个

<div class="form-group">
    <div class='result'>{{dataAjax}}</div>
 </div>

如果您返回的HTML数据与应用程序有关,也许您可以考虑使用$scope$apply()来更新DOM。