使用$ watch两个变量angularjs

时间:2014-10-10 07:34:17

标签: angularjs angularjs-scope

我有一个弹出屏幕,用户需要从两个下拉列表中进行选择。 选择完成后,我将选择返回给服务并将其保存在对象中。

app.service('OriginalService', [ '$modal',

function ($modal) {
var that = this;

this.filtersMananger = { // my-ng-models for the two drop-down-lists
    firstFilter: "",
    secondFilter: ""
};

this.openDialog = function(){
    var modalInstance = $modal.open({
        templateUrl: 'ModalScreen.html',
        controller: 'ModalController',
        resolve: {
            filtersManagerObject: function () {
                return that.filtersMananger;
            }
        }
    });

    modalInstance.result.then(function (filtersMananger) {
        that.filtersMananger.firstFilter = filtersMananger.selectedFirstFilter;
        that.filtersMananger.secondFilter = filtersMananger.selectedSecondFilter;
    }, function () {

    });
};
}
 ]);

弹出html:

<div class="data-filters-container">
 <div class="data-filter">
    <label for="filter-data-drop-down">FIRST FILTER</label>
    <select name="filterDataDropDown" ng-model="filtersMananger.selectedFirstFilter" ng-options="filter.value as filter.name for filter in filterDropDownItems"></select>
</div>
  <div class="data-filter col-xs-4">
    <label for="filter-data-drop-down">SECOND FILTER</label>
    <select name="filterDataDropDown" ng-model="filtersMananger.selectedSecondFilter" ng-options="filter.value as filter.name for filter in filterDropDownItems"></select>
</div>

然而,这一变化很重要,我必须致电知道许多其他服务的控制器向他们发送有关此更改的信息。

为了做到这一点,我在控制器中使用了一个监视功能:

 $scope.$watch('OriginalService.filtersMananger.firstFilter + OriginalService.filtersMananger.secondFilter', function (newVal, oldVal) {

        if (newVal !== oldVal) {

           DO SOME LOGIC
        }
    });

我在newVal和oldVal之间进行比较,因为当上传应用程序时,会调用该事件并进入此函数。

问题是newVal只包含secondVariable的值。 有没有想到为什么newVal也不包含第一个变量?

2 个答案:

答案 0 :(得分:1)

使用$watchCollection

$scope.$watchCollection('[serviceName.Object.firstVariable,serviceName.Object.secondVariable]', function (newValues, oldValues) {

});

或者,如果您使用的是角度1.3,请使用$watchGroup

$scope.$watchGroup(['serviceName.Object.firstVariable','serviceName.Object.secondVariable'],function(newValues, oldValues){

})

答案 1 :(得分:0)

您还可以在选择中使用ng-change。 ng-change将调用一个执行逻辑的函数

<div class="data-filters-container">
   <div class="data-filter">
      <label for="filter-data-drop-down">FIRST FILTER</label>
      <select name="filterDataDropDown"  ng-change="checkFilterOne()" ng-model="filtersMananger.selectedFirstFilter" ng-options="filter.value as filter.name for filter in filterDropDownItems"></select>
  </div>
  <div class="data-filter col-xs-4">
    <label for="filter-data-drop-down">SECOND FILTER</label>
    <select name="filterDataDropDown" ng-change="checkFilterTwo()" ng-model="filtersMananger.selectedSecondFilter" ng-options="filter.value as filter.name for filter in filterDropDownItems"></select>
</div>

当您的模型发生变化时,它会调用该功能,就像$ watch一样。