角度不更新范围更改时的模板

Angular not updating template on scope change

本文关键字:更新 范围      更新时间:2023-09-26

当输入框中的日期更改时,我正在尝试更新我的模板。

我的输入框 html 是:

<div class="col-md-4 pull-right">
    <input type="text" id="id_date" class="form-control" ng-model="date" ng-change="sendPost()" value="{{ date }}"/>
</div>

我的表模板是:

<tr>
    <td style="font-weight: bold">term</td>
    <td ng-repeat="block in blocks">{{ data[block]['term'] }}</td>
    <td>{{ total['term'] }}</td>
</tr>

最后我的控制器代码是:

$scope.blocks = ['A', 'B', 'C'];
$scope.data = {'A': {'term': 0, 'term2': 7}, 'B': {'term': 2, 'term2': 3}, 'C': {'term': 5, 'term2': 14}};
$scope.total = {'term': 50, 'term2': 70};
$scope.date = "2016-01-01";
$scope.sendPost = function() {
    //console.log("working");
    var post_data = {"date": $scope.date};
    $http.post("/web_api", post_data).success(function (post_data, status) {
        $scope.data = post_data.data;
        $scope.total = post_data.total;
        console.log($scope.data);
        console.log($scope.total);
    }).error(function(response) {
        //console.log(response);
          $scope.error = 'ERROR';
      });
};

控制台日志在 post 请求中返回所需的对象。

每当你在 angularjs 之外执行某种形式的操作时,你需要让 angular 知道更新自身。

尝试添加 $scope.$apply();

之后
$scope.data = post_data.data;
$scope.total = post_data.total;

在您的帖子请求中,它可能会起作用。

查看更多关于 $scope.$apply() 的信息

.success.error已被弃用,但仍有效。但是,它们给出原始数据响应。

您正在尝试使用response.data但没有这样的事情。

// This is the old way. It still works, but you get a raw data response.
$http.post("/web_api", post_data).success(function (post_data, status) {
    $scope.data = post_data;  // <-- Fixed!
    $scope.total = post_data.total; // <-- There is no such thing.
    console.log($scope.data);
    console.log($scope.total);
}).error(function(response) {
    //console.log(response);
      $scope.error = 'ERROR';
  });

更好的是,使用新方式:

$http.post(...).then( onSuccess, onError );

onSuccess中,您可以使用 $scope.data = post_data.data;

$http.post(...).then(function(post_data){
    $scope.data = post_data.data;
});

除此之外,您的代码工作正常。我彻底尝试了一下。

https://docs.angularjs.org/api/ng/service/$http#deprecation-notice

尝试将

范围分配块包装在$timeout中,这会将操作发送到 que 的末尾。喜欢这个:

$http.post("/web_api", post_data).success(function (post_data, status) { $timeout(function(){ $scope.data = post_data.data; $scope.total = post_data.total; console.log($scope.data); console.log($scope.total); }); }).error(function(response) { //console.log(response); $scope.error = 'ERROR'; });

你的$http承诺是不同的。检查 https://docs.angularjs.org/api/ng/service/$http

试试这个:

$http
.post('/web_api', post_data)
.then(function(response) {
    // success
    $scope.data = post_data.data;
    $scope.total = post_data.total;
    console.log($scope.data);
    console.log($scope.total);
}, function(response) {
    // error
    //console.log(response);
    $scope.error = 'ERROR';
})
.finally(function() {
    // finally.. like for disable loader ?! 
});