简体   繁体   English

双向绑定似乎不起作用。 列表未自动更新

[英]two way binding doesn't seem to work. List is not automatically updating

I'm having troubles updating a list. 我在更新列表时遇到麻烦。 At first I fill my list by fetching information from a $http.get request. 首先,我通过从$ http.get请求中获取信息来填充列表。 Later I enter something in a text box and I try to update the list with the response of the $http.post request. 稍后,我在文本框中输入内容,然后尝试使用$ http.post请求的响应来更新列表。

I do get a response and I have the data. 我确实得到了答复,并且我有数据。 When I overwrite the variable that is in $scope the list doesn't update. 当我覆盖$ scope中的变量时,列表不会更新。

My code looks like this: 我的代码如下所示:

 'use strict'; angular.module('myApp.friends', ['ngRoute']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/friends', { templateUrl: 'friends/friends.html', controller: 'FriendsCtrl' }); }]) .controller('FriendsCtrl', function ($scope, $http, $timeout, UserService) { $scope.items = []; $scope.formSearchData = {}; UserService.getAll().then(function(data) { var remoteItems = data; for (var i = 0; i < remoteItems.length; i++) { var object = {}; object.name = remoteItems[i].name; object.id = remoteItems[i]._id; $scope.items.push(object); } }); $scope.itemClick = function(value) { console.dir(value); }; $scope.submitForm = function() { //debugger; $scope.items[0].name = "John D"; UserService.getSearchResult($scope.formSearchData).then(function(data) { getSearchResult(data); }); }; function getSearchResult(data) { var remoteItems = data.records; $scope.items = []; for (var i = 0; i < remoteItems.length; i++) { var object = {}; object.name = remoteItems[i].name; object.id = remoteItems[i].id; $scope.items.push(object); } } }) .controller('navigationcontroller', function ($scope, $location) { $scope.isActive = function(viewLocation) { return viewLocation = $location.path(); } }); 
 <div class="panel panel-title"> <div class="panel-body"> <div class="friend-search" ng-controller="FriendsCtrl"> <form ng-submit="submitForm()"> <input type="search" name="search" placeholder="Zoek vrienden" class="form-control" ng-model="formSearchData.search"> </form> </div> </div> </div> <div class="panel panel-title"> <div class="panel-default"> <div class="scrollable-content" ui-scroll-bottom='bottomReached()' ng-controller="FriendsCtrl"> <div class="list-group"> <a ng-repeat="item in items" ng-model="items" class="list-group-item" ng-click="itemClick(item)"> {{ item.name }} </a> </div> </div> </div> </div> 

The UserService is a factory that has the two functions, one for the GET request and one for the POST request. UserService是一个工厂,具有两个功能,一个用于GET请求,另一个用于POST请求。 It looks like this: 看起来像这样:

 angular.module('myApp').factory('UserService', function($http) { return { getAll: function() { return $http.get('http://localhost:3030/user/all').then(function(response) { return response.data; }); }, getSearchResult: function(query) { return $http.post('http://localhost:3030/user/search', query, { 'Content-Type': 'application/json' }).then(function(response) { return response.data; }); } }; }); 

I read something about $scope being out of scope and try to solve it by using $scope.apply() or $scope.$digest but I get errors when I try that. 我读到一些有关$ scope超出范围的内容,并尝试通过使用$ scope.apply()或$ scope。$ digest来解决,但尝试此操作时出现错误。 Also I tried adding tracking in the html but that also doesn't seem to work. 我也尝试在html中添加跟踪,但这似乎也不起作用。

As you can see I also tried to hardcode update the list, that also doesn't seem to work. 如您所见,我还尝试对列表进行硬编码,这似乎也不起作用。

I'm very new to Angular and this is keeping me busy for days now. 我是Angular的新手,现在让我忙了好几天。 I hope someone can help me. 我希望有一个人可以帮助我。 Any suggestions to my code are welcome as well ;) . 也欢迎对我的代码提出任何建议;)。 Thanks! 谢谢!

Here is a plunker of your code working with just one controller. 这是仅使用一个控制器即可完成的代码编写工作。 I modified it a little since I don't have your API endpoints, but the returned object is a promise and hence data gets displayed correctly. 由于没有您的API端点,我对其做了一些修改,但是返回的对象是一个Promise,因此可以正确显示数据。

http://plnkr.co/edit/iEWBm6QE2pmFqbsU6EiB?p=preview http://plnkr.co/edit/iEWBm6QE2pmFqbsU6EiB?p=preview

The reason your code doesn't work as you intend is because you have declared the controller twice in the HTML. 您的代码无法按预期工作的原因是因为您在HTML中两次声明了控制器。

From the angular docs: 从角度文档:

"When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be created and made available as an injectable parameter to the Controller's constructor function as $scope." “当通过ng-controller指令将Controller附加到DOM时,Angular将使用指定的Controller的构造函数实例化一个新的Controller对象。将创建一个新的子作用域并将其作为可注入的参数提供给Controller的构造函数作为$ scope。”

Meaning: 含义:

When you declare another ng-controller, it has its own child scope, it does not share scope with any other controller. 当您声明另一个ng-controller时,它具有自己的子作用域,它不与任何其他控制器共享作用域。 And your items are declared on only one scope. 并且您的项目仅在一个范围内声明。

Relevant code: 相关代码:

var app = angular.module("myApp", []);

app.controller('myCtrl', ['$scope', 'UserService', function($scope, UserService){

  $scope.items = [];

  $scope.formSearchData = {};

  UserService.getAll().then(function(data) {
      $scope.saved = data;

      for (var i = 0; i < $scope.saved.length; i++) {
          var object = {};
          object.name = $scope.saved[i].name;
          object.id = $scope.saved[i]._id;
          $scope.items.push(object);
      }
  });

  $scope.itemClick = function(value) {
      console.dir(value);
  };

  $scope.submitForm = function() {
      UserService.getSearchResult($scope.formSearchData).then(function(data) {
          console.log( data );
          if( data ){
            $scope.items = data;
          } else {
            $scope.data = $scope.saved;
          }

      });
  };



}]); 

app.factory('UserService', function($http, $q) {
    return {
        getAll: function() {
          return $q(function(resolve, reject) {
            resolve(
              [{
                name: 'test'
              }, {
                name: 'test2'
              }]
            );
          });
            /*return $http.get('http://localhost:3030/user/all').then(function(response) {
                return response.data;
            });*/
        },

        getSearchResult: function(query) {
          return $q(function(resolve, reject) {
            resolve( [{
              name: 'test'
            }]);
          });
          /*  return $http.post('http://localhost:3030/user/search', query, { 'Content-Type': 'application/json' }).then(function(response) {
                return response.data;
            });*/
        } 
    }; 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM