【问题标题】:Angular.js - Slicing a json request according to user inputAngular.js - 根据用户输入对 json 请求进行切片
【发布时间】:2017-08-17 13:21:35
【问题描述】:

我是 Angular.js 的初学者,目前正在使用 tutorial。我决定尝试让用户更改显示的手机数量。在我的控制器中:

function PhoneListController($http) {
  var self = this;
  self.orderProp = 'age';

  $http.get('phones/phones.json').then(function(response) {
    self.phones = response.data.slice(0, self.displayNum); 
  });
}
PhoneListController.$inject = ['$http']; //services to inject for each parameter in PhoneListController

我根据用户输入的 displayNum 对从服务器获取的响应数据进行切片。我确信 displayNum 已在模型中更新,但它并没有像我预期的那样对 json 进行切片。 http请求是不是一开始就只发出一次?

我模板的相关部分:

<p>
  Number of phones displayed:
  <input ng-model="$ctrl.displayNum" />
</p>
...
<ul class="phones">
  <li ng-repeat="phone in $ctrl.phones | filter:$ctrl.query | orderBy:$ctrl.orderProp">
    <span>{{phone.name}}</span>
    <p>{{phone.snippet}}</p>
  </li>
</ul>
<p>display num: {{$ctrl.displayNum}}</p>

底部的display num: {{$ctrl.displayNum}}会根据&lt;input ng-model="$ctrl.displayNum" /&gt;中输入的数字进行更新,但列表大小不变。如果我在控制器中硬编码self.displayNum 的值,则刷新页面时列表会被正确切片,但更改输入中的值对列表没有任何作用。

【问题讨论】:

  • 你应该在更新displayNum模型后再次调用http服务。
  • 您能详细说明一下吗?我将如何再次调用http?有没有办法检查模型是否发生了变化?
  • 成功了,谢谢!

标签: javascript html angularjs


【解决方案1】:

正如@Alexander-Bolzhatov 所提到的,我只是将 http 请求放在一个 change 函数中,由模板中的 ng-change 调用。

  $http.get('phones/phones.json').then(function(response) {
    self.phones = response.data; 
  });

  self.change = function(){
    $http.get('phones/phones.json').then(function(response) {
      self.phones = response.data.slice(0, self.displayNum); 
    });
  };

模板代码:

Number of phones displayed:
    <input ng-model="$ctrl.displayNum" ng-change="$ctrl.change()"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-09
    • 2022-11-19
    • 1970-01-01
    • 2021-04-04
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多