范围问题 - 页面未从兄弟控制器中的http帖子更新

时间:2018-01-08 20:20:57

标签: angularjs angularjs-scope

我正在使用ng-click来调用请求范围新内容的函数。我通过调用由php处理的帖子请求来做到这一点。 当我运行脚本时,我可以在控制台中看到更新的数据,但页面没有更新。

HTML;

'use strict';

var angular_app = angular.module('angular_app', []);



    angular_app.controller('objectCtrl', ['$scope','$http', function ($scope,$http) {
        $http({
            method: 'get',
            url: 'ajax-processor.php'
        }).then(function successCallback(response) {
            $scope.objects = response.data;
        });
     }]);

     angular_app.controller('objectNavCtrl', ['$scope','$http', function ($scope,$http) {

        $scope.update = function(){
            console.log('clicked');
            $http({
                method: 'post',
                url: 'ajax-processor.php',
                data:  {'ajaxKey':'Mykey'}
            }).then(function successCallback(response) {
                $scope.objects = response.data;
                console.log(response.data);
            });
        }
     }]);

AngularJS app;

library(data.table)

dt <- data.table(x=rep(c("a","b"),20),y=factor(sample(letters,40,replace=T)), z=1:20)

i <- 15
new_var <- paste0("new_",i)

# my attempt
dt[, .( eval(new_var) = sum( z[which( z <= i)] )), by= x]

# expected result
dt[, .( new_15 = sum( z[which( z <= i)] )), by= x]

>    x new_15
> 1: a    128
> 2: b    112

我在加载页面时使用get方法,并尝试使用更新函数更新它。

2 个答案:

答案 0 :(得分:1)

问题是两个控制器位于不同的范围内。将公共数据放在父控制器的范围内:

<body>
  <!-- Common scope -->
  <div ng-controller="parent as common">

    <!-- Separate Scope -->
    <div ng-controller="objectNavCtrl" id = "content">
      <a ng-click="update()">link</a>
    </div>

    <!-- Separate Scope -->
    <div ng-controller="objectCtrl" >
      ̶<̶d̶i̶v̶ ̶i̶d̶=̶"̶o̶b̶j̶e̶c̶t̶_̶c̶o̶n̶t̶a̶i̶n̶e̶r̶"̶ ̶n̶g̶-̶r̶e̶p̶e̶a̶t̶=̶"̶o̶b̶j̶e̶c̶t̶ ̶i̶n̶ ̶o̶b̶j̶e̶c̶t̶s̶ ̶t̶r̶a̶c̶k̶ ̶b̶y̶ ̶o̶b̶j̶e̶c̶t̶.̶i̶d̶"̶>̶ 
                                              <!--use common scope here -->
      <div id="object_container" ng-repeat="object in common.objects track by object.id">
        <div>{{object.name}}</div>
      </div>
    </div>

  </div>
</body>
angular_app.controller('objectNavCtrl', ['$scope','$http', function ($scope,$http) {

    $scope.update = function(){
        console.log('clicked');
        $http({
            method: 'post',
            url: 'ajax-processor.php',
            data:  {'ajaxKey':'Mykey'}
        }).then(function successCallback(response) {
            ̶$̶s̶c̶o̶p̶e̶.̶o̶b̶j̶e̶c̶t̶s̶ ̶=̶ ̶r̶e̶s̶p̶o̶n̶s̶e̶.̶d̶a̶t̶a̶;̶
            $scope.common.objects = response.data;
            console.log(response.data);
        });
    }
 }]);

有关详细信息,请参阅

答案 1 :(得分:0)

您正在按ID跟踪更改。因此,只要对象的ID不会改变,页面就不会被刷新。尝试离开轨道或获得更好的性能,使用您比较的某些属性或您自己的比较器功能执行此操作:ng-repeat with track by over multiple properties