Angular & Apache - $scope更新,但需要单击某处才能显示在界面上



我的项目后端使用PHP编写,前端使用Angular.js,服务器运行在Linux下的Apache。
问题是,任何时候我想重定向到新的页面,如$location.path("/home")我必须点击身体的某个地方影响!
或者有时从ajx GET或POST方法获取数据,$作用域更新,但没有显示,直到点击身体的某个地方!

这是路由配置:

app.config(['$routeProvider', 
    function ($routeProvider) {
        $routeProvider
        .when('/home', {
            templateUrl: 'views/home/home.html',
            controller: 'homeControllers',
            caseInsensitiveMatch : true
        })
        .when('/', {
            templateUrl: 'views/home/home.html',
            controller: 'homeControllers'
        })
        .otherwise('/')
        ;
    }
]);

这是我的POST服务:

app.factory("method", function(primaries) {
    return {
        POST: function(url, obj, callBack) {
            $.ajax({
                url: primaries.urls.baseUrl + url,
                method: 'POST',
                dataType: 'json',
                data: obj,
                success: function(data) {
                    if (callBack) {
                        return callBack(data);
                    }
                    return data;
                },
                error: function(data) {
                    //console.log('ERROR on ' + url);
                },
            });
        }
    }     
});

我是这样填充$scope的:

method.POST("/est/view", {"test":"test"}, function(data) {
    $scope.param = data;
})

顺便说一下,我尝试了$scope.$apply(),但没有改变!
在使用本地数据的windows中,我没有在Localhost上遇到这些问题。
有什么问题吗?

这些问题很可能是由于你使用的是jQuery的$.ajax而不是Angular的$http.post。如果您真的想要使用jQuery的版本,这是可行的,但可能不值得这样做。

把你的代码改成:

app.factory("method", function($http, primaries) {
    return {
        POST: function(url, obj) {
            return $http.post(url, obj);
        }
    }     
});

然后在控制器中:

method.POST("/est/view", {"test":"test"}).then(function(data) {
    $scope.param = data;
});
需要注意的是PHP不能很好地读取作为JSON发送的POST数据,所以你需要让Angular作为表单数据发送,或者像这样读取JSON POST数据:
$_JSON = json_decode(file_get_contents('php://input'), true);
if (!empty($_JSON)) {
    $_POST = $_JSON;
} 

最新更新