Mahesh Singh Chouhan
Mahesh Singh Chouhan

Reputation: 2588

AngularJS: How to bind a $scope variable to another $scope.variable

I want to bind a $scope.variable to another $scope.variable like this:

$scope.b = '';
$scope.a = $scope.b;
$scope.b = 10;
console.log($scope.a);// It gives blank value

In other words, i want to assign $scope.b value to $scope.a whenever $scope.b get a value.

Upvotes: 2

Views: 6802

Answers (5)

zion
zion

Reputation: 421

$watch will be called everytime $scope.a changes. If you have multiple data, then you can create a JSON instead of individual variables

$scope.tmp = {
  'b' : 22,
  'a' : 33
};
$scope.$watch('tmp', function() {
   $scope.tmp.a = $scope.tmp.b; // Set $scope.a here
}, true);

Upvotes: 2

Ankit Pundhir
Ankit Pundhir

Reputation: 1097

In javascript you can copy objects references, As what you are doing is copying the value of b to a even if you want to copy the reference. Because $scope.b is primitive type data. If you want to copy its reference it should be of non-primitive type. as,

$scope.b = {c:''};
$scope.a = $scope.b;
$scope.a.c = 10;
console.log($scope.b.c); //output 10

Upvotes: 0

mrahhal
mrahhal

Reputation: 3497

You must do a watch:

$scope.$watch('b', function (newValue) {
    $scope.a = newValue;
});

$scope.b = 2;
Console.log($scope.a); // Careful! This will still be undefined, explanation below.

Angular has a digest loop that it executes to process bindings. If you want you can do a $scope.$apply() to instruct angular to run the loop or you can just leave it to do its thing, that's probably what you want in real code.

Upvotes: 3

JLRishe
JLRishe

Reputation: 101758

You can use Object.defineProperty() to define one property in terms of another:

function myController($scope) {
  Object.defineProperty($scope, 'b', {
    get: function() {
      return $scope.a;
    },
    set: function(value) {
      $scope.a = value;
    }
  });
  
  $scope.b = 10;
  console.log($scope.a);
  $scope.a = 20;
  console.log($scope.b);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="myController">
    <input type="text" ng-model="a" />
    <input type="text" ng-model="b" />
  </div>
</div>

Upvotes: 1

Serhii Kozachenko
Serhii Kozachenko

Reputation: 1401

In JavaScript you can copy reference to the obj and it will give you what you expect.

You need to do this:

$scope.b = {prop: 0};
$scope.a = $scope.b;
$scope.b.prop = 10;
console.log($scope.a.prop);// It gives 10

Upvotes: 6

Related Questions