0

I tried to implement the below functionality. There are 2 text boxes. When we type on box 1 the box 2 will also have the value of box 1 and vice versa.

using the same ng-model will do this, but I need to learn how to use elements(references) and identify them in a controller to do this

<body ng-app="myApp" ng-controller="myControl">
    Name 1 : <input type="text" ng-model="name1"  ng-change="change1()" />

    Name 2 : <input type="text"  ng-model="name2" ng-change="change2()" >
</body>

var app = angular.module('myApp', []);
app.controller('myControl',function($scope,$http){ 

$scope.change1 = function(){
    $scope.name2= $scope.name1;
}
$scope.change2 = function(){
    $scope.name1= $scope.name2;
}

});

Fiddle of the code

How can I use one function instead of using the two functions change1 and change2( I think if I pass a reference it can be done. But i could not find a way to do that) ?

prime
  • 14,464
  • 14
  • 99
  • 131

2 Answers2

1

By making the the ng-model value structure like object, then Javascript prototypal will do the trick, While you are assigning name1 object to name2 they both will follow the same object, as update in any of the value array will update other. Thats the reason why we don't want such feature then we uses cloning of object, In jQuery its .clone() & in angular its known as angular.copy which creates a new deep copy of the object which will not follow this rule.

Markup

Name 1 : <input type="text" ng-model="name1.value"/>

Name 2 : <input type="text"  ng-model="name2.value"/>

Code

var app = angular.module('myApp', []);
app.controller('myControl',function($scope,$http){ 
    $scope.name1= {};
    $scope.name2= {};
    $scope.name1= $scope.name2; //will update two object according no need of ng-change
});

Forked Fiddle

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • it works (Y). I'm trying to learn here since I'm new to AngularJS. Can you please tell how this works ? I mean how `$scope.name1= $scope.name2;` actually do this ? – prime Jun 08 '15 at 14:46
  • I mean when first one changes it will do `$scope.name1= $scope.name2;` , is it like making it the value of the next text box , which is empty ?? – prime Jun 08 '15 at 14:47
  • @prime take a look at update..and read the reference link will give you more idea,, – Pankaj Parkar Jun 08 '15 at 14:57
1

Just have a look at this code you call same function on ng-change and it works fine

<body ng-app="myApp" data-ng-controller="MainCtrl" id="div1">
  Name 1 : <input type="text" ng-model="name1"  ng-change="change1(name1)" />

    Name 2 : <input type="text"  ng-model="name2" ng-change="change1(name2)" />

 <script>
  var app = angular.module('myApp', []);

  app.controller('MainCtrl', function($scope){

    $scope.change1 = function(val){
     $scope.name2= val;
     $scope.name1=val;
    }


    });
  </script>


</body>
shreyansh
  • 1,637
  • 4
  • 26
  • 46