【问题标题】:AngularJs ng-change never firedAngularJs ng-change 从未被解雇
【发布时间】:2016-05-04 14:52:00
【问题描述】:

当我在框中键入内容时,h1 文本会相应更改。所以,ng-model 工作正常。

但是,alert 函数永远不会被触发。为什么?

<html lang="en" ng-app>
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <title></title>
  <script type="text/javascript" src="angular.min.js"></script>
</head>
<body>
  <input type="text" ng-model="name" ng-change="alert('name changed')">
  <h1>Hello3, {{name}}</h1>
</body>
</html>

Angular 1.5.5

更新 这是带有@stackdisplay评论的工作版本:

<html lang="en" ng-app="myApp" ng-controller="AppCtrl">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="bootstrap.min.css">
  <title></title>
  <script type="text/javascript" src="angular.min.js"></script>
  <script type="text/javascript">
    var app = angular.module("myApp",[]);
    app.controller('AppCtrl', function($scope) {
      $scope.myfunc = function(text) { window.alert(text); }
    })
  </script>
</head>
<body>
  <input type="text" ng-model="name" ng-change="myfunc('name changed')">
  <h1>Hello, {{name}}</h1>
</body>
</html>

这是有效的。但是,如果我不实现myfunc(或以前的alert 函数),为什么我不会收到控制台错误?

如果window 是一个全局变量(同样,控制台中没有任何错误),为什么使用@think_win_win 建议的window.alert 不起作用?

【问题讨论】:

  • 尝试写window.alert('name changed')。该函数将根据当前的 $scope 进行评估,因为您可能没有定义 $scope.alert 函数,所以没有任何反应。
  • 我试过window.alert,但两者都没有。另外,我在 chrome 开发者控制台上没有收到任何错误消息。
  • 该语法正在触发 $scope.alert ,因此如果您没有实际的 $scope.alert 函数,则不会发生任何事情。

标签: angularjs


【解决方案1】:

根据Stackoverflow Post Answer

在 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 在这里可用,但这将使您的代码更 从长远来看很难测试。

【讨论】:

  • 如果你提到的定义一个控制器,它就可以工作。我已经用这些信息更新了这个问题。但是,如果我不实现'local0 警报功能,为什么我不会收到控制台错误?以及为什么使用 @think_win_win 建议的 window.alert 不起作用,如果 window 是一个全局变量(同样,在控制台中没有任何错误)?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-07
  • 2011-06-21
  • 1970-01-01
  • 2013-05-22
  • 2012-11-18
相关资源
最近更新 更多