本文介绍了使用 ng-change 设置 $scope.myModel 元素进入无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Angular 还很陌生,并试图实现一些基本"的目标.我已经用谷歌搜索了 2 天没有成功,希望得到一些帮助.

I'm pretty new to Angular and trying to achieve something "basic". I've been googling for 2 days without success and would appreciate some help.

我有一个 html 页面,我正在尝试:

I have an html page on which I'm trying to:

  1. 使用 HTTP POST 请求初始化数据
  2. 当用作过滤器的元素发生更改(即类别、按 asc/desc 排序...)时,通过 ng-change 事件调用函数以使用另一个 HTTP POST 更新数据

我的问题是,当我使用 HTTP 响应(仅在这种情况下)以编程方式更新模型时,它会触发附加到元素的 ng-change 事件,该事件本身调用更新函数,然后进入无限循环:ng-change -> 更新函数 -> ng-change -> 更新函数

My problem is that when I'm updating the model programmatically with the HTTP response (only in this case), it triggers the ng-change event attached to the element, which itself calls the update function and then enters in an infinite loop:ng-change -> updating function -> ng-change -> updating function

注意:我使用的是 Angular Material 模板,但它不会更改代码

HTML

<html ng-app="MyApp">
    <body layout="column" ng-controller="SearchServiceController">
        <h1 class="md-headline">Filter results</h1>
        <form name="searchServiceForm" novalidate>
            <md-input-container>
                <md-select placeholder="Choose category" ng-model="searchService.selectedCategory" ng-change="changedSearchServiceCriteria()">
                    <md-option ng-value="category.value" ng-repeat="category in listOfCategories">{{ category.title }}</md-option>
                </md-select>
             </md-input-container>
             <md-input-container>
                 <md-select placeholder="Sort by" ng-model="searchService.sortBy" ng-change="changedSearchServiceCriteria()">
                     <md-option ng-value="criteria.value" ng-repeat="criteria in sortByCriterias">{{ criteria.title }}</md-option>
                  </md-select>
              </md-input-container>
          </form>
          <h1 class="md-headline">{{ selectedCategory.title }}</h1>
          <p class="md-body-1">{{ selectedCategory.description }}</p>
    </body>
</html>

JS

var app = angular.module('MyApp', ['ngMaterial']);

app.controller('SearchServiceController', function($scope, $http, $location) {
  // Initialize data using the category id parameter in the URL
  $http({
    method: 'POST',
    url: '/projets/get-offerings-list',
    data: {selectedCategory: $location.path().split("/")[4]},
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
      .success(function(response) {
        alert('INIT');
        $scope.listOfCategories = response.listOfCategories;
        $scope.sortByCriterias = response.sortByCriterias;
        $scope.searchService = response.searchService;
      })
      .error(function(response) {
        console.log('Failure occured');
      });

  // Update data
  $scope.changedSearchServiceCriteria = function() {
    $http({
    method: 'POST',
    url: '/projets/get-offerings-list',
    data: {selectedCategory: $location.path().split("/")[4]},
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
      .success(function(response) {
        alert('UPDATE');
        $scope.listOfCategories = response.listOfCategories;
        $scope.sortByCriterias = response.sortByCriterias;
        $scope.searchService = response.searchService;
      })
      .error(function(response) {
        console.log('Failure occured');
      });
  };
});

结果

INIT
Object {listOfCategories: Array[3], sortByCriterias: Array[2], searchService: Object}
UPDATE
Object {listOfCategories: Array[3], sortByCriterias: Array[2], searchService: Object}
UPDATE
Object {listOfCategories: Array[3], sortByCriterias: Array[2], searchService: Object}
UPDATE
Object {listOfCategories: Array[3], sortByCriterias: Array[2], searchService: Object}
UPDATE
Object {listOfCategories: Array[3], sortByCriterias: Array[2], searchService: Object}
UPDATE
Object {listOfCategories: Array[3], sortByCriterias: Array[2], searchService: Object}
....infinite loop....

当我在不使用 HTTP 请求响应的情况下以编程方式更新模型时,不会发生这种情况.请参阅此处:http://plnkr.co/edit/baNjr85eAOkKVu4dnf1m?p=preview关于如何在不引发 ng-change 事件的情况下更新表单元素,您有什么想法吗?

This doesn't occur when I'm updating the model programmatically without using the response of the HTTP request. See here: http://plnkr.co/edit/baNjr85eAOkKVu4dnf1m?p=previewWould you have any ideas on how I could update the form element without provoking the ng-change event?

谢谢

请注意,我不想使用 $watch 那样的解决方法:ngChange 以编程方式更改模型时调用

Please note that I do not want to use a workaround using $watch like there: ngChange is called when model changed programmatically

推荐答案

您应该尝试将一个工作示例添加到 http://jsfiddle.net/ 或类似的.

You should try to add a working example into http://jsfiddle.net/ or similar.

我会猜测并且没有经过测试,您需要保留上次搜索,并且仅在每次获取新地址(或在 JS 中调用的任何内容)发生更改时才运行更新 AJAX 请求 - 即使它相同的值并重新评估

I would think at a guess and not tested that you need to keep the last search and only run the update AJAX request if it changes as it gets a new address (or whatever thats called in JS) every time - even though its the same value and re evaluates again

$scope.searchService = "";
$scope.lastSearch = ""

// Update data using form elements
$scope.changedSearch = function() {

    if($scope.searchService != $scope.lastSearch){

      $http({
        method: 'POST',
        url: '/projects/get-list',
        data: $scope.searchService,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
      })
        .success(function(response) {
            // Request succeeded? Display message
            console.log('UPDATE');
            console.log(response);
            // Update data
            $scope.listOfCategories = response.listOfCategories;
            $scope.sortByCriterias = response.sortByCriterias;
            $scope.searchForm = response.searchForm;
        })
          .error(function(response) {
            // Request failed? Display message
            console.log('Failure occured');
        })
          .complete(function(response) {
            // do after success or error
            $scope.lastSearch = $scope.searchService;
            console.log('complete');
        });
    }
};

这篇关于使用 ng-change 设置 $scope.myModel 元素进入无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:12
查看更多