为什么Angular.js叫我的功能,所以经常与NG-变化以及如何让每个变化调用一次? [英] Why is Angular.js calling my function so frequently with ng-change and how do I make it call only once per change?

查看:94
本文介绍了为什么Angular.js叫我的功能,所以经常与NG-变化以及如何让每个变化调用一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经过很多的教程将建立后我的第一个适当的angular.js应用程序。我已经打与 ngChange 指令的一个问题。我试图用它每一个下拉列表中的值由用户改变时调用的函数。我发现它在页面加载函数多次,也多次选中该选项,每次通话。

I'm building my first proper angular.js app after going through many tutorials. I've hit a problem with the ngChange directive. I'm trying to use it to call a function each time the value of a drop down list is changed by the user. I find that it calls the function multiple times upon page load and also multiple times each time the option is selected.

我已经把本的jsfiddle 这证明我有这个问题。

I've put together this jsfiddle which demonstrates the problem I'm having.

我想知道为什么它的出现此行为,我怎么能达到我期望的每份期权改变一个函数调用,并没有的调用变化()的结局页面加载。 (这第二个标准是对我的应用程序不太重要,但我想知道如何燮preSS这种行为仍然)。

I'd like to know why it's exhibiting this behaviour and how I can achieve my desired outcome of one function call per option change and no calling of change() on page load. (this second criterion is less critical for my app, but I would like to know how to suppress this behaviour nonetheless).

我转载低于code对于那些你谁可能是能够找到一个直接的错误。

I've reproduced the code below for those of you who may be able to find an immediate error.

<body ng-app ng-controller="Controller">
<div>
    <h2>Number of changes: {{numOfChanges}}</h2>
    <select ng-change="{{change()}}" ng-model="currentSelection">
    <option ng-repeat="option in options">{{option}}</option>
    </select>
</div>
</body>

的JavaScript

Controller = function($scope) {
    $scope.numOfChanges = 0;
    $scope.change = function() {
        $scope.numOfChanges++;
    }
    $scope.options = ["do", "ray", "me", "far", "so", "la", "tee","dah"]
}

我知道这很可能是由于角的方法我的不当使用/理解。我倒是认为解决这个小例子的所有缺点AP preciate答案。

I'm aware this could well be due to my improper use/understanding of the angular methodology. I'd appreciate answers that address all the failings of this small example.

推荐答案

NG-变化中的任何内容已经被认可的角度,所以你不需要包装在{{}​​}。刚 NG-变化=更改()就行了。

Anything inside ng-change is already recognised by angular, so you don't need to wrap it in {{ }}. Just ng-change="change()" will do.

在括号结束语会造成棱角分明,以评估它在页面加载和更新其观点的任何时间,因此它发射多次。

Wrapping it in braces will cause angular to evaluate it on page load and any time it updates the view, hence it firing multiple times.

这篇关于为什么Angular.js叫我的功能,所以经常与NG-变化以及如何让每个变化调用一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆