为什么我的改变事件没有被解雇?

时间:2015-12-16 22:19:12

标签: javascript html angularjs

标题几乎解释了这一切。我从w3学校举了一个例子。

  <html>
  <head>
    <title>Example: Change event on a select</title>
    <script type="text/javascript">
      function changeEventHandler(event) {
        alert('You like ' + event.target.value + ' ice cream.');
      }
    </script>
   </head>
    <body>
        <label>Choose an ice cream flavor: </label>
        <select size="1" onchange="changeEventHandler(event);">
            <option>chocolate</option>
            <option>strawberry</option>
            <option>vanilla</option>
        </select>
    </body>
</html>

我运行警报框时会运行它。但是,当我运行代码时,我无法弹出警报框:

HTML

 <!DOCTYPE html>
<html lang="en-US">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="myCtrl.js"></script>
<body>

<div ng-app="myTestApp" ng-controller="myCtrl">

    <p>Looping with ng-repeat:</p>
    <label>Job Accounts</label>
    <select id="jobList" size="1" ng-model="selectedJobServer" onchange="myFunction()">
      <option ng-repeat="x in jobServers" value="{{x}}">{{x}}</option>
    </select> 

    <label>Oracle Accounts</label>
    <select ng-disabled={{isDisabled}} ng-model="selectedOracleServer">
      <option ng-repeat="x in oracleServers" value="{{x}}">{{x}}</option>
    </select>

    <p>The selected server is: {{selectedJobServer}}</p>
</div>

</body>
</html>

JS

 var app = angular.module('myTestApp', []);
app.controller('myCtrl', function($scope) {

    $scope.isDisabled = true;

    $scope.jobServers = ['server1','server2','server3'];

    function myFunction(){
        alert("Hello! I am an alert box!");
    }
});

是否存在与角色的某些互动而引发问题?谢谢。

2 个答案:

答案 0 :(得分:3)

您的功能应该在$scope

因此,您可以将myCtrl代码修改为

$scope.myFunction = function(){
   alert("Hello!");
}

此外,您应该将活动从change修改为ng-change

<select id="jobList" size="1" ng-model="selectedJobServer" ng-change="myFunction()">
  <option ng-repeat="x in jobServers" value="{{x}}">{{x}}</option>
</select> 

答案 1 :(得分:1)

如果您使用角度,请使用角度全押。不要声明泛型函数,声明角度函数:

$scope.myFunction =  function (){
    alert("Hello! I am an alert box!");
}

并且不要使用onChange事件,请使用ng-change:

 <select id="jobList" size="1" ng-model="selectedJobServer" ng-change="myFunction()">