How to watch two expressions that have separate listeners in angularjs?

I need to look at two expressions so that each expression has a separate listener. so I wrote two $ watch () methods. Is it possible to write as in one hour statement.

Thanks for the answer hooray, I want to say that for each expression it has a separate listener (I have two expressions and two listeners, i.e. one listener for one expression and another listener for the second expression) as it can be used with single hours ().

+3


source to share


3 answers


https://plnkr.co/edit/JvJQ90tLcpS0x79ZnDvr?p=preview



<html ng-app="angularjs-starter">

<head lang="en">
  <meta charset="utf-8">
  <title>Controller example Plunker</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
  <link rel="stylesheet" href="style.css">
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <script src="app.js"></script>
</head>

<body>
  <h1>Welcome Watch</h1>

  <div ng-controller="SpicyCtrl">
    <div>
      <label>First</label>
      <input type="text" ng-model="watch1" />
    </div>
    <br/>
    <div>
      <label>Second</label>
      <input ng-model="watch2" />
    </div>


    <p>First input value{{watch1}}</p>
    <p>Second input value {{watch2}}</p>

  </div>


</body>

</html>
var app = angular.module('angularjs-starter', []);

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

   $scope.$watch('[watch1,watch2]',function(a,b,c){

      if((b[0]!==undefined||a[0]!==undefined) && b[0]!==a[0]){
        //functionality for first watchtrigger
        alert('watch1 changed')
      }
      if((b[1]!==undefined||a[1]!==undefined) && b[1]!==a[1]){
         //functionality for second watchtrigger
        alert('watch2 changed')
      }

    })

});

      

+2


source


You can use $watchGroup

or$watchCollection

Create an array of your other expression and you will get the result in one list :)



Docs

Hope this helps :)

0


source


Try it.

$scope.$watch('[first,second]', function () { ... }, true);

      

LINK

0


source







All Articles