Angularjs从另一个作用域中的作用域中删除项



下面是我使用角度站点的数据得到的东西的模型。目标是删除作用域2(新设备)中已经存在于作用域1(设备)中的任何项目。我有一个工作模式,但觉得这不是最好的方法。

我有一个控制器,它从两个不同的来源提取数据。为了简单起见,我将第一个作用域设置为静态,而第二个作用域将通过httpget从angular站点获取数据,这是通过单击按钮启动的。(我的prod代码需要使用一个按钮,这样我就可以在调用中注入变量)

app.controller('customersCtrl', function($scope, $http) {
//Example static data for scope 1
$scope.devices = [
   {"Name":"Around the Horn","City":"London","Country":"UK"},
   {"Name":"B's Beverages","City":"London","Country":"UK"},
   {"Name":"Chop-suey Chinese","City":"Bern","Country":"Switzerland"}
];
//scope 2 data from angular example site that is initiated from a button
$scope.loaddata = function() {
  $http.get("http://www.w3schools.com/angular/customers_mysql.php")
    .then(function (response) {
        $scope.newdevices = response.data.records;
      });
  }
});

然后我有一个过滤器来比较范围:

app.filter('matcher', function() {
  return function(newdevices, devices) {
    var array2Ids = []
    angular.forEach(devices, function(value, index) {
      array2Ids.push(value.Name);
    })
  return newdevices.filter(function(val) {
    return array2Ids.indexOf(val.Name) === -1;
  })
 }
});

最后,我将过滤器应用于我的ng重复调用:

<div ng-app="myApp" ng-controller="customersCtrl">
<button ng-click="loaddata()">load me</button>
  <table>
    <tr ng-repeat="x in newdevices | matcher: devices">
      <td width="300px">{{ x.Name }}</td>
      <td width="150px">{{ x.City }}</td>
      <td width="100px">{{ x.Country }}</td>
    </tr>
  </table>
</div>

如前所述,这目前是可行的,但由于我已经从一个函数中调用了第二个作用域httpget,有没有一种方法可以将过滤器集成到loaddata函数中,这样它就可以同时发生,并且可以消除在ng重复阶段进行过滤的需要?

我对此还比较陌生,还没能完成。

您不需要角度"过滤器"。只需在将响应数据分配给$scope.newdevices之前对其进行筛选。下面的代码已经过测试,但您已经明白了。

$scope.loaddata = function() {
$http.get("http://www.w3schools.com/angular/customers_mysql.php")
.then(function (response) {
      //do things here, i.e.
       var array2Ids = [];
       angular.forEach(devices, function(value, index) {
         array2Ids.push(value.Name);
       });
       $scope.newdevices = response.data.records.filter(function(val) {
           return array2Ids.indexOf(val.Name) === -1;
       });
    });
}

控制器和服务可以使用$filter服务检索过滤器。

var matcherFn = $filter('matcher');
var result = marcherFn(newdevices, devices);

AngularJS过滤器既可以在模板中使用,也可以在JavaScript中使用。

文档中的示例:

angular.module('filterExample', [])
.controller('MainCtrl', function($scope, $filter) {
  $scope.originalText = 'hello';
  $scope.filteredText = $filter('uppercase')($scope.originalText);
});

有关更多信息,请参阅AngularJS$filter Service API参考。

最新更新