AngularJs ng-change从未被解雇过

时间:2016-05-04 14:52:01

标签: angularjs

当我在框中输入内容时,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函数),为什么我不会收到控制台错误?

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

1 个答案:

答案 0 :(得分:3)

按照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可用,但这会让您的代码更多   从长远来看很难测试。

相关问题