Search code examples
javascriptangularjsangular-directive

Monitor changes with a directive


I have a form where I am using ng-repeat in a few places to output some data from different arrays. Also there is a 'Add item' button that is supposed to add an item to the array. Something like this:

-----------FORM--------------
|      [add button]         |
|                           |
|   ------------------      |
|   | ng-repeat array1|     |
|   -------------------     |
|       [add button]        |
|   ------------------      |
|   | ng-repeat array2|     |
|   -------------------     |
|                 [save]    |
----------------------------- 

So I wanted to make save button visible using ng-disabled, only if there's a change in any of the arrays. For example by default save would be disabled, but when I add new item to the array1 and that item is then rendered, I want save to be visible. Also if the newly added element is removed from the array, save should be aware that default state is restored and save should be disabled.

I'm not sure how to approach this problem to create something reusable, should it be a directive? Is there maybe a solution that I could use to implement this ?


Solution

  • try this

    $scope.oldModel = { text:'val',text2:'val2'}
    $scope.model = { text:'val',text2:'val2'}
    
    $scope.btnDisabled= true;
    

    watch scope

    $scope.$watch('model.text + model.text2',
      function(newVal, oldVal) {
        if(JSON.stringify($scope.oldModel) !== JSON.stringify($scope.model)){
            $scope.btnDisabled= false;
        }
        else{
            $scope.btnDisabled= true;
        }
      }
    );
    

    or

    $scope.$watch('model',
      function(newVal, oldVal) {
        if(JSON.stringify($scope.oldModel) !== JSON.stringify(newVal)){
            $scope.btnDisabled= false;
        }
        else{
            $scope.btnDisabled= true;
        }
      },
      true
    );