简单的ng-change在angularjs中无法正常工作

时间:2014-05-27 06:28:34

标签: javascript angularjs

由于这个简单的代码不能按预期工作,我可能会错过一些愚蠢的东西。有什么问题是MainCtrl中的$scope.change函数不起作用(没有弹出警告框)。

简而言之,视图是(它在玉中,更适合查看?)

<body ng-app="epfApp">
...
label(ng-repeat="question in questions")
    | {{ question.title }}
    input(type="{{question.type}}", ng-change="change()")

并在控制器文件中

angular.module('epfApp')
.controller('MainCtrl', function ($scope, $window) {

    $scope.questions = {
        '1': {
                'title': 'The first question is?',
                'type': 'text',
                'placeholder': 'first question'
            },

        '2': {
                'title': 'The second question is?',
                'type': 'text',
                'placeholder': 'second question'
            }
    };

    $scope.change = function() {
        $window.alert('text');
    };

});

路线:

$routeProvider
  .when('/', {
    templateUrl: 'views/main.html',
    controller: 'MainCtrl'
  });

现在它正在做的是它正确地用创建的数据填充视图(即问题json)。但是,绑定到输入文本框的 change() 函数无法正常工作。

我在这里缺少什么?这显然是一项非常基本的工作。

4 个答案:

答案 0 :(得分:22)

ng-change也需要ng-model

<div ng-controller="MainCtrl">
    <label ng-repeat="question in questions">
        {{question.title}}
        <input type="{{question.type}}" ng-model="question.placeholder" ng-change="change()" />
        <br />
    </label>
</div>

Check out this JSFiddle.

答案 1 :(得分:3)

ng-change无效但如果你定义ng-model =“yourValue”就可以了...就像这样

<select id="editSelect" ng-model="Option" ng-change="okChange()" name="Option">
    <option ng-repeat="data in Option" value="{{data.Option}}">{{data.Option}}</option>
</select>

答案 2 :(得分:1)

<div ng-app ng-controller="myCtrl">
<input type="file" ng-model="image" onchange="angular.element(this).scope().uploadImage()" />
<ul>
   <li ng-repeat="item in uploadcollection">
     {{item.name}}  ({{item.size}})
   </li>
</ul>

function myCtrl($scope) {
    $scope.uploadImage = function () {
        $scope.uploadcollection.push({name: "Income.pdf", size: "10mb"});
        $scope.$apply();
}
$scope.uploadcollection = [{name: "Income.pdf", size: "10mb"}, {name: "Expense.pdf", size: "1.5mb"}];
}

我在这里创建了一个演示:http://jsfiddle.net/fA968/120/

注意:此示例不适用于v1.4.8:https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js

<强>更新 这是一种简单的方法:

var myApp = angular.module('myApp', []);
myApp.directive('customOnChange', function() {
return {
 restrict: 'A',
 link: function(scope, element, attrs) {
   var onChangeFunc = scope.$eval(attrs.customOnChange);
      element.unbind('change').bind('change', function(e) {
        onChangeFunc(e);
      });
   }
  };
});

Here是一个更新的小提琴

答案 3 :(得分:0)

ng-change=""内的表达式出现错误(例如拼写错误)时,它将不会将该错误记录到控制台。除了什么都没发生的事实之外,您将不知道什么是不对的。

请确保正确拼写事物,并为别名加上“ Controller As”语法(如果适用)。