-1

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 ?

Zed
  • 5,683
  • 11
  • 49
  • 81
  • Have a look at angular's form [directive](https://docs.angularjs.org/api/ng/directive/form) and [controller](https://docs.angularjs.org/api/ng/type/form.FormController). – Cerbrus Apr 28 '15 at 11:48

3 Answers3

0

Firstly you can just enable [save] button if some of [add button] were clicked. Secondly you can use the code to watch changes in array1 and array2:

scope.$watch('array1',
function (newVal, oldVal) {
 if(!newVal.equals(oldVal)) {
   scope.enableShowButton = true;
 }
},true)

Use the answer from How to compare arrays in JavaScript? to effectively compare two arrays. or just use angular.equals

Community
  • 1
  • 1
Oleksandr Papchenko
  • 2,071
  • 21
  • 30
0

You can do this in 2 steps :

First, when you create a element in your array add a tag to your created element (somthing like "new: true").

And in your ng-disabled call a method who look into your array to find a "new: true" and in this case return false.

0

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
);