1

我想使用$watchCollection以跟蹤我的指令中的兩件事情。

  1. ng-model

  2. 這是id屬性。

我知道如何分別看每一個。

return { 
     restrict: 'A', 
     require: 'ngModel', 
     scope: { 
      options: '=', 
      model: '=ngModel' 
     }, 
     link: function ($scope, $el, $attrs) { 
      scope = $scope; 
      $scope.$watch(
       function() { 
        return $el[0].id; 
       }, 
       function (elementId) { 
        $('#' + elementId).on('switch-change', function() { 
         scope.model[this.id] = $(this).find('input').is(':checked'); 
         $scope.$apply(); 
        }); 

        $('#' + elementId)['bootstrapSwitch'](); 
        $('#' + elementId).bootstrapSwitch('setOnLabel', _($('#' + elementId).attr('data-on-label'))); 
        $('#' + elementId).bootstrapSwitch('setOffLabel', _($('#' + elementId).attr('data-off-label'))); 
       }); 
      $scope.$watchCollection('model', function(newval){ 
       if(typeof newval !== 'undefined' && !$.isEmptyObject(newval)){ 
        // do some stuff here 
       } 
      }); 
     } 
    } 

但我想獲得的所有變量在同一個函數.. 謝謝

回答

0

如果更改角的ID,那麼你可以使用virable作爲id,然後一個範圍只是看變種

<div id="{{directiveId}}"></div> 

然後您可以使用$ watchGroup或$ watchCollection一起觀察directiveId和model。