调用AJAX后如何刷新Angular范围?

时间:2018-06-29 10:14:14

标签: angularjs ajax

我在此处添加到灯箱的功能无法正常工作:http://icon.pha-group.com/,因为我的Angular应用已在AJAX内容之前加载。我知道我需要以某种方式从AJAX成功中调用Angular应用程序,但是我不确定如何。这样做的原因是在其他页面上没有动态加载内容。成功了:

$.ajax({
//url: bobz.ajax_url,
url: "/wp-admin/admin-ajax.php",
data: {
    action: 'do_filter_posts',
nonce: bobz.nonce,
params: $params
},
type: 'post',
dataType: 'json',
success: function(data, textStatus, XMLHttpRequest) {

    if (data.status === 200) {
        $content.html(data.content);
    }
    else if (data.status === 201) {
        $content.html(data.message);    
    }
    else {
        $status.html(data.message);
    }

    //all done so call cycle script
    script_cycle();
    // Cookies.set('pageA-selection', '#page=3  ');
    //console.log(data.content);
 },

这是我的Angular添加到灯箱应用程序的开始:

var app = angular.module('lightbox', ['ngSanitize']);

app.controller('lightboxCtrl', function($scope, $http) {

function IsJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}


$http.get('/wp-admin/admin-ajax.php?action=lightbox_list_ajax').success(function(data) {

    if (typeof(Storage) !== "undefined" &&
        localStorage.getItem("lightbox_list") !== null ||
        localStorage.getItem("lightbox_list"))
    {
        var selectedOption = localStorage.lightbox_list;


    //} else if(data)
    //{
    //    var selectedOption = data[0];
    //
    //    localStorage.setItem("lightbox_list", JSON.stringify(selectedOption));

    }else{
        var selectedOption = null;
    }

    if(IsJsonString(selectedOption))
    {
        $scope.data = {
            availableOptions: data,
            selectedOption: JSON.parse(selectedOption) //This sets the default value of the select in the ui
        };

    }else{

        $scope.data = {
            availableOptions: data,
            selectedOption: selectedOption //This sets the default value of the select in the ui
        };
    }

console.log(selectedOption);
}).error(function(){
    console.log('unable to load lightbox lists');
});

1 个答案:

答案 0 :(得分:0)

在ajax响应中使用$scope.$apply()

success: function(data, textStatus, XMLHttpRequest) {

    if (data.status === 200) {
        $content.html(data.content);
    }
    else if (data.status === 201) {
        $content.html(data.message);    
    }
    else {
        $status.html(data.message);
    }

    //all done so call cycle script
    script_cycle();
    $scope.$apply()
 },

但是请注意,使用$ajax成角度是非常不好的习惯。使用$http服务,它是内置的角度服务,您无需在$ http中调用$apply