Angular ng-change not calling code. Am I using wrong model

杀马特。学长 韩版系。学妹 提交于 2019-12-23 01:12:08

问题


I am building an app using MEAN.js generators and a tutorial I found online. Here I have a datepicker in one of my Angular views. For now I would like the ng-change directive to be recognized and do something. At the moment when I make a change to the date my test alert shown here does not get called.

<div class="form-group">
   <label class="control-label" for="statusdate">Status Date</label>
   <div class="controls">
      <input type="date"  ng-change="alert('something')" data-ng-model="statusDate" id="statusdate" class="form-control">
   </div>
</div>

Can somebody help? I am new to Angular.

Also, I read somewhere it may be because I used data-ng-model as opposed to ng-model. Could this be the case? If so then what is the difference between the two?


回答1:


You are executing a method that does not exist in the controller.

Try creating it like this:

$scope.alert = function(msg) {
    alert(msg);
 };



回答2:


Ah, the problem is, you don't have the context you think you do.

Almost everywhere in Javascript, the root of all the closures is window, which contains alert().

Almost everywhere, but not everywhere. Not in the context in which that ng-change() is evaluated. You could fix it by, for example, creating a controller that added a value called alert to the $scope, and pointing it to window.alert.

<div class="form-group">
   <label class="control-label" for="statusdate">Status Date</label>
   <div class="controls" ng-controller="myController">
      <input type="date"  ng-change="alert('something')" data-ng-model="statusDate" id="statusdate" class="form-control">
   </div>
</div>

And then in the Javascript:

angular.module("MyApp")
.controller("myController", ['$scope', '$window', function($scope, $window) {
  $scope.alert = $window.alert;
}]);

Edit: you could use just window instead of $window, because window is available here, but that will make your code more difficult to test in the long run.




回答3:


The problem is ng-change is expecting an expression, but you're giving it a function name alert() to display the string 'something', and hence, it doesn't know what to do.

A possible solution to this is to add this on top of your HTML file

<script>
  angular.module('Your_App_Name', [])
    .controller('YourControllerName', ['$scope', '$window', function($scope, $window) {
      $scope.alert = function(message) {
          $window.alert(message);
      };
   }]);
</script>

Refer to the documentation for more info on how to use ng-change https://docs.angularjs.org/api/ng/directive/ngChange

Refer to difference b/w ng-model and data-ng-model to understand the difference between data-ng-model and ng-model. They should both work fine.



来源:https://stackoverflow.com/questions/31152013/angular-ng-change-not-calling-code-am-i-using-wrong-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!