关于javascript:在$ http发布请求后,使用AJAX重新加载部分模板

我对AngularJS还是比较陌生,所以请耐心等待。我正在尝试创建一个照片喜欢系统,当用户单击"喜欢"按钮时,它会增加"喜欢"的次数。我已经关闭了此功能,但是唯一的是我必须重新加载页面才能显示"喜欢"。这意味着后端上的所有东西都井井有条。但是,我想避免必须重新加载页面。

要注意的一件事是,我有一个局部模板,并且使用ng-click指令单击按钮后,就会发生HTTP发布请求。

部分模板中的HTML片段

1
Like

AngularJS

1
2
3
4
5
6
7
8
9
10
11
userApp.controller('photoController',['$scope','$location','$window','$log','$route','$routeParams','$location','$http', function($scope,$location,$window,$log,$route,$routeParams,$location,$http){
    $scope.name = 'Photos';
    $scope.likeIt = function(parameters){
        $http.post('centralcommand.php', {id: parameters}).success(function(data,status,headers,config){
            window.location.reload(); // Causes page to reload
               }).error(function(data,status,headers,config){
            alert('failure');
        });
    };

}]);

也请注意,我已尝试更改成功回调中的innerHTML。这是行不通的,因为我已经将PHP与HTML混合使用,并且必须在HTML代码中同时使用'",所以当我获取HTML文本并使用innerHTML替换它时,它将无法正常工作。


我仔细研究了一种不同的方法后就找到了答案,它来自于单独的StackOverflow帖子中提供的答案。它与使用$templateCache服务重新加载模板缓存有关:

1
2
3
4
5
6
7
8
9
10
11
12
13
userApp.controller('photoController',['$scope','$location','$window','$log','$route','$routeParams','$location','$http','$templateCache', function($scope,$location,$window,$log,$route,$routeParams,$location,$http,$templateCache){
    $scope.name = 'Photos';
    var currentPageTemplate = $route.current.templateUrl; // ADDITION # 1
    $scope.routeReloader = function(parameters){
        $http.post('centralcommand.php', {id: parameters}).success(function(data,status,headers,config){
            $templateCache.remove(currentPageTemplate);   // ADDITION # 2
            $route.reload();                              // ADDITION # 3
               }).error(function(data,status,headers,config){
            alert('failure');
        });
    };

}]);