1

假设两个输入字段 - 名称和文本。如何同时观看这两个字段并将它们的值插入到一个表达式中?

谢谢!

更新2014年9月7日:
我这样做Plunkr的代码:)

感谢穆罕默德Sepahvand的工作版本!

代码:

<!doctype html> 
    <html ng-app="myApp"> 
    <head> 
     <title>Interpolate String Template Example</title> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.js"></script> 
     <script type="text/javascript"> 
     angular.module('myApp', ['emailParser']).controller('MyController', ['$scope', 'EmailParser', function ($scope, EmailParser) { 
      // init 
      $scope.to = ''; 
      $scope.emailBody = ''; 

      $scope.$watchCollection('[to, emailBody]', function (newValues, oldValues) { 
      // do stuff here 
      // newValues and oldValues contain the new and respectively old value 
      // of the observed collection array 
      if (newValues[0] && newValues[1]) { // there's name and some text? 
       $scope.previewText = EmailParser.parse(newValues[1], {to: $scope.to}); 
      } 
     }); 
     }]); 

     angular.module('emailParser', []).config(['$interpolateProvider', function ($interpolateProvider) { 
      $interpolateProvider.startSymbol('__'); 
      $interpolateProvider.endSymbol('__'); 
     }]).factory('EmailParser', ['$interpolate', function ($interpolate) { // create service 
      return { 
      parse: function (text, propertiesToBeInterpolated) { // handle parsing 
       var template = $interpolate(text); 
       return template(propertiesToBeInterpolated); 
      } 
      }; 
     }]); 
     </script> 
    </head> 
    <body> 
     <h3>Instructions in readme.md file - please read before!</h3> 
     <div id="emailEditor" ng-controller="MyController"> 
     <label>*Name:</label> 
     <input ng-model="to" type="text" placeholder="Ex.: John"/> 
     <br><br> 
     <label>*Text:</label><br> 
     <textarea ng-model="emailBody" cols="25" rows="10" placeholder="Write something"></textarea> 
     <p style="color:red;">*required</p> 
     <div> 
      <pre>__previewText__</pre> 
     </div> 
     </div> 
    </body> 
    </html> 

回答

2

可以使用$watchGroup方法是在角1.3增加:

$scope.$watchGroup(['prop1', 'prop2'], function(newValues, oldValues, scope) { 
    var prop1 =newValues[0]; 
    var prop2 =newValues[1]; 
}); 

或者你可以使用$watchCollection因为角1.1.4已被查阅:

scope.$watchCollection('[prop1, prop2]', function(newValues, oldValues){ 

}); 
相关问题