使用 ng-model 更新函数

Updating functions using the ng-model

更改最后一条消息时,我需要做什么才能使消息保持更新? 先感谢您。

   angular.module('myApp',[]).controller('MessageController', function($scope) {
     getMessage = function(x){
        return "Hello, " + x + ":)";
      }
     $scope.lastMessage = "Whosebug";
     $scope.message = getMessage($scope.lastMessage);    
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
      <div ng-controller="MessageController">
        <input type="text" ng-model="lastMessage" ng-model-options="{allowInvalid: true}">
        <p ng-bind="lastMessage"></p>
        <p ng-bind="message"></p>
      </div>  
    </body>

您可以在最后一条消息的 ng-change 上调用 getMessage 函数:

 angular.module('myApp',[]).controller('MessageController', function($scope) {
 $scope.getMessage = function(x){
     $scope.message = "Hello, " + x + ":)";
  }
 $scope.lastMessage = "Whosebug";    
});


<body ng-app="myApp">
   <div ng-controller="MessageController">
    <input type="text" ng-model="lastMessage" ng-change="getMessage(lastMessage)" ng-model-options="{allowInvalid: true}">
    <p ng-bind="lastMessage"></p>
    <p ng-bind="message"></p>
  </div>  
</body>

您可以试试下面的代码,

模板:

<input type="text" ng-model="lastMessage" ng-change="getMessage(lastMessage)" ng-model-options="{allowInvalid: true}">
<p ng-bind="lastMessage"></p>
<p ng-bind="message"></p>

控制器代码:

$scope.getMessage = function(x){
  $scope.lastMessage = x;
  $scope.message = "Hello, " + x + ":)";
}
$scope.getMessage('Whosebug');

尝试观察 lastMessage 变量:

$scope.$watch('lastMessage ', function() {
    $scope.message = "Hello, " + $scope.lastMessage + ":)";;
});

有关 watchapply 的更多信息,请查看 here

angular.module('myApp',[]).controller('MessageController', function($scope) {
     $scope.lastMessage = "Whosebug";
     $scope.message=$scope.lastMessage;
     $scope.aa="";
     $scope.bb="";
     $scope.$watch('lastMessage',function(){
        $scope.message= "Hello, " + $scope.lastMessage + ":)";
      });
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

 <body ng-app="myApp">
      <div ng-controller="MessageController">
        <input type="text" ng-model="lastMessage" ng-model-options="{allowInvalid: true}">
        <p ng-bind="lastMessage"></p>
        <p ng-bind="message"></p>
      </div>
      <p>
        <p ng-bind="aa"></p>
        <p ng-bind="bb"></p>
      </p>
    </body>

试试这个

  <div ng-controller="MessageController">
    <input type="text" ng-model="lastMessage" ng-model-options="{allowInvalid: true}">
    <p ng-bind="lastMessage"></p>
    <p ng-bind="getMessage(lastMessage)"></p>
  </div>  

您有使用 ng-bind 或函数的特定原因吗?因为对于这样的事情你可以这样做

  <input type="text" ng-model="lastMessage" ng-model-options="{allowInvalid: true}">
  <p>{{lastMessage}}</p>
  <p ng-if="lastMessage.length"> Hello {{lastMessage}} :)</p>

ng-if 以防万一你只想在用户输入内容时显示消息。