2

我正在使用 MEAN.js 生成器和我在网上找到的教程构建一个应用程序。在这里,我的一个 Angular 视图中有一个日期选择器。现在我希望 ng-change 指令被识别并做一些事情。在我更改日期时,此处显示的测试警报不会被调用。

<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>

有人可以帮忙吗?我是 Angular 的新手。

另外,我在某处读到可能是因为我使用了 data-ng-model 而不是 ng-model。会是这样吗?如果是这样,那么两者之间有什么区别?

4

3 回答 3

3

啊,问题是,你没有你认为的上下文。

在 Javascript 中几乎所有地方,所有闭包的根window都是alert().

几乎无处不在,但并非无处不在。不在ng-change()评估的上下文中。例如,您可以通过创建一个控制器来修复它,该控制器将一个名为 的值添加alert$scope,并将其指向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>

然后在 Javascript 中:

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

编辑:您可以只使用window而不是$window, 因为window在此处可用,但这会使您的代码从长远来看更难以测试。

于 2015-07-01T03:26:12.597 回答
2

您正在执行控制器中不存在的方法。

尝试像这样创建它:

$scope.alert = function(msg) {
    alert(msg);
 };
于 2015-07-01T03:25:26.637 回答
0

问题是 ng-change 需要一个表达式,但是你给它一个函数名 alert() 来显示字符串 'something',因此,它不知道该怎么做。

一个可能的解决方案是将其添加到您的 HTML 文件之上

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

有关如何使用 ng-change https://docs.angularjs.org/api/ng/directive/ngChange的更多信息,请参阅文档

请参阅区别 b/w ng-model 和 data-ng-model以了解 data-ng-model 和 ng-model 之间的区别。他们都应该工作正常。

于 2015-07-01T03:33:30.353 回答