AngularJS ng-click fires twice - javascript

I am using ng-click and it fires twice when I apply it to SPAN tag.
HTML
<div ng-app="regApp" ng-controller="RegistrationCtrl" data-ng-init="GetEventDetail()" ng-show="data.EventName">
<h2>Registration for {{data.EventName}}</h2>
<span class="btn" id="btnSave" ng-click="PostRegistration()">Save </span>
</div>
CONTROLLER
var app = angular.module('regApp', ['ui']);
app.controller('RegistrationCtrl', function ($scope, $http) {
$scope.PostRegistration = function () {
alert('click '); <--- fires twice
/// some code here --
};
It should only fire once. How I can find why this is happening and how to fix it?

The code you've provided does not fire the event twice:
http://jsfiddle.net/kNL6E/ (click Save)
Perhaps you included Angular twice? If you do that, you'll get two alerts, demonstrated here:
http://jsfiddle.net/kNL6E/1/

I had a similar problem, but could not find where I included Angular twice in my files.
I was using an ajax calls to load specific form layouts, so I need to use $compile to activate Angular on the inserted DOM. However, I was using $compile on my directive $element which has a controller attached. Turns out this "includes" the controller twice, causing two triggers with ng-click or ng-submit.
I fixed this by using $compile directly on the inserted DOM instead of my directive $element.

Same problem using
<a ng-click="fn()"></a>
fn was called twice
Using a button fixed it :
<button ng-click="fn()"></button>

This is probably obscure, but I had ng-click firing twice because I had BrowserSync running, which would mirror my inputs into a tab that I had open in another window, thus doubling up all my clicks. To resolve, I disabled “ghostMode”: https://www.browsersync.io/docs/options/

I solved this by removing my ngsubmit handler as I don't have a need for it. I'm monitoring on change events and using SignalR to update the screen in near real-time.
I was also in a form and the AngularJS docs for ngSubmit states:
Warning: Be careful not to cause "double-submission" by using both the ngClick and ngSubmit handlers together. See the form directive documentation for a detailed discussion of when ngSubmit may be triggered.

In case of somebody having the same issue:
This was my problem:
<a type="submit" ng-click="login()">submit login<a>
Both, the type="submit" and the ng-click="login()"triggered the login()-method in my controller.
So just use either the type=submit or the ng-click directive

If other answers don't help, make sure that AngularJS profiling is disabled in Batarang (if you have it installed of course).
This was making ng-click to fire twice for me.

elements wrapped one another, and this can cause trigger event twice or more.
So i used a simple CSS trick for this solution :
.off{
pointer-events:none;
}
and apply it to an element correspond to click event.

You might have a ng-click inside a form container using a ng-submit. In that case, add type="button" to all your using ng-click.

I got it when I accidently called $compile for the dynamically added elements several times in the cycle, instead of just once. Compiling just once removed this effect.

was facing same issue.
Find out they were using https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js version and i switch it to latest 1.4.5 version and it just worked.
https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js
var app = angular.module('regApp', []);
app.controller('RegistrationCtrl', ['$scope','$http',function($scope,$http ) {
$scope.PostRegistration = function() {
alert('click '); // <--- fires twice
/// some code here --
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="regApp" ng-controller="RegistrationCtrl">
<h2 >Registration for {{data.EventName}}</h2>
<span ng-click="PostRegistration()" class="btn" id="btnSave">Save </span>
</div>

I have changed <button ng-click='clickHandler()'> to <a ng-click='clickHandler()'> and now event fires only once

I've had the same issue when dynamically injecting partial views in my SPA(Single Page Applications).The way I solved it was to store the content of my div in a local variable like this:
var html = $("#leftContainer").html();
Then empty out the div and reset its content like this:
$("#leftContainer").empty();
$("#leftContainer").append(html);
Now you can add any additional html you have received from an AJAX call or dynamically constructed and lastly remember to re-compile your HTML to make it bound to angular:
var entities = $("#entitiesContainer");
var entity = "<div><a href='#' ng-click='Left(" + entityId + ")'> " + entityName + "</a><div>"
entities.append(entity);
var leftContainer = angular.element(document.getElementById("entitiesContainer"));
$compile(leftContainer)($scope);

I'm a bit of a dummy and had this:
<li data-shape="amethyst" ng-click="toggleGem('amethyst')">
<label></label>
<i class="amethyst"></i>Amethyst
<input type="checkbox" name="gem_type" id="gem-amethyst" value="amethyst" />
</li>
The click event was triggering twice. I moved the ng-click to the label element and it's working as expected.
<li data-shape="amethyst">
<label ng-click="toggleGem('amethyst')"></label>
<i class="amethyst"></i>Amethyst
<input type="checkbox" name="gem_type" id="gem-amethyst" value="amethyst" />
</li>

This situation may be caused by lacking the ngTouch in Angular.
Event if the ngTouch is loaded, the bug in ngTouch and ngClick before Angular 1.5.0 may occur. It results from the ngClick being triggered by pointerup and mouseUp in Chrome for Desktop on device toolbar or mobile device.

I had a problem like this as well.
<button style="width: 100%;" class="btn btn-danger" ng-click="'{{vm.delete()}}'">
Thats not how you call ng-click, but no errors were thrown and the function calls still worked.
<button style="width: 100%;" class="btn btn-danger" ng-click="vm.delete()">
Is correct and will then only be called once.

I don't know what was the reason this happened, but I had to use event.stopPropagation(); inner my JavaScript function.
HTML
<button class="button" ng-click="save($event)">Save</button>
JAVASCRIPT
function save(event) {
event.stopPropagation();
}

I have handled it by following code
HTML :
<div>
<ui>
<li>
<button class="Button" ng-disabled="self.desableSubmitButton" ng-
click="self.SubmitClick($event)">Submit</button>
</li>
</ui>
</div>
Angular 1.0 Controller :
_self.SubmitClick = function(event){
_self.desableSubmitButton = true; //disable submit button
event.preventDefault();
event.stopPropagation();
setTimeout(funtion() {
_self.desableSubmitButton = false; //enable submit button after timeout
if(_self.$scope.$$phase != '$apply' || _self.$scope.$$phase != '$digest'){
_self.$scope.$digest();
}
}, 1000);//other Code logic
}

My case: I used ng-click event on my custom custom angular checkbox component. So just providing a method binding for custom component did the trick.
Before:
<mono-checkbox-ng ng-click="vm.onSelectAllClicked()">
After:
<mono-checkbox-ng on-changed="vm.onSelectAllClicked()">

Related

Disabling submit button based on fields added with ng-bind-html

JSFiddle here: http://jsfiddle.net/c6tzj6Lf/4/
I am dynamically creating forms and buttons and want to disable the buttons if the required form inputs are not completed.
HTML:
<div ng-app="choicesApp">
<ng-form name="choicesForm" ng-controller="ChoicesCtrl">
<div ng-bind-html="trustCustom()"></div>
<button ng-repeat="button in buttons" ng-disabled="choicesForm.$invalid">
{{button.text}}
</button>
</ng-form>
</div>
JavaScript:
angular.module('choicesApp', ['ngSanitize'])
.controller('ChoicesCtrl', ['$scope', '$sce', function($scope, $sce) {
$scope.custom = "Required Input: <input required type='text'>";
$scope.trustCustom = function() {
return $sce.trustAsHtml($scope.custom);
};
$scope.buttons = [
{text:'Submit 1'},
{text:'Submit 2'}];
}]);
choicesForm.$invalid is false and does not change when entering text into the input field.
Solution:
I ended up using the angular-bind-html-compile directive from here: https://github.com/incuna/angular-bind-html-compile
Here is the relevant bit of working code:
<ng-form name="choicesForm">
<div ng-if="choices" bind-html-compile="choices"></div>
<button ng-click="submitForm()" ng-disabled="choicesForm.$invalid">
Submit
</button>
</ng-form>
And choices might be a snippit of HTML like this:
<div><strong>What is your sex?</strong></div>
<div>
<input type="radio" name="gender" ng-model="gender" value="female" required>
<label for="female"> Female</label><br>
<input type="radio" name="gender" ng-model="gender" value="male" required>
<label for="male"> Male</label>
</div>
The main problem is that ngBindHtml doesn't compile the html - it inserts the html as it is. You can even inspect the dynamic input and see that it doesn't have the ngModel's CSS classes (ng-pristine, ng-untouched, etc) which is a major red flag.
In your case, the form simply doesn't know that you've added another input or anything has changed for that matter. Its state ($pristine, $valid, etc) isn't determined by its HTML but by the registered NgModelControllers. These controllers are added automatically when an ngModel is linked.
For example this <input required type='text'> won't affect the form's validity, even if it's required, since it doesn't have ngModel assigned to it.
But this <div ng-model="myDiv" required></div> will affect it since it's required and has ngModel assigned to it.
The ngDisabled directive on your buttons works as expected since it depends on the form's $invalid property.
See this fiddle which showcases how ngModel registers its controller. Note that the html containing the dynamic input gets compiled after 750ms just to show how NgModelControllers can be added after FormController has been instantiated.
There are a few solutions in your case:
use a custom directive to bind and compile html - like this one
use ngInclude which does compile the html
use $compile to compile the newly added HTML but this is a bit tricky as you won't know exactly when to perform this action
This is an answer yet imcomplete because i cannot do the code at the moment.
I think your html will be included, not compiled. So the inputs are not bind to angular and are not part of the angular form object.
The only way i see is to use a directive that will compile the passed html and add it to your form. This may be quite tricky though, if you want to go on this way i suggest to edit your question to ask for the said directive.
However i'm not really familiar with $compile so i don't know if it'll work to just add $compile around $sce.trustAsHtml()
You can write a method as ng-disabled does not work with booleans, it works with 'checked' string instead:
So on your controller place a method :
$scope.buttonDisabled = function(invalid){
return invalid ? "checked" : "";
};
And on your view use it on angular expression :
<button ng-repeat="button in buttons" ng-disabled="buttonDisabled(choicesForm.$invalid)">
Here is a working fiddle
Working DEMO
This is the solution you are looking for. You need a custom directive. In my example I have used a directive named compile-template and incorporated it in div element.
<div ng-bind-html="trustCustom()" compile-template></div>
Directive Code:
.directive('compileTemplate', function($compile, $parse){
return {
link: function(scope, element, attr){
var parsed = $parse(attr.ngBindHtml);
function getStringValue() { return (parsed(scope) || '').toString(); }
//Recompile if the template changes
scope.$watch(getStringValue, function() {
$compile(element, null, -9999)(scope); //The -9999 makes it skip directives so that we do not recompile ourselves
});
}
}
});
I found the directive in this fiddle.
I believe what is really happening though due to jsfiddle I'm unable to dissect the actual scopes being created here.
<div ng-app="choicesApp">
<ng-form name="choicesForm" ng-controller="ChoicesCtrl">
<div ng-bind-html="trustCustom()"></div>
<button ng-repeat="button in buttons" ng-disabled="choicesForm.$invalid">
{{button.text}}
</button>
</ng-form>
</div>
The first div is your top level scope, your form is the first child scope. Adding the div using a function creates the dynamically added input field as a child of the first child, a grandchild of the top level scope. Therefore your form is not aware of the elements you're adding dynamically causing only the static field to be required for valid form entry.
A better solution would be to use ng-inclue for additional form fields or if your form isn't to large then simply put them on the page or template you're using.

On click function parameters Knockout

I am trying to pass one parameter to a function by knockout click binding. If i try sending it without binding, it works.
Here is the fiddle of the working code without binding:
https://jsfiddle.net/Obviously/ev0Lcx7q/4/
But if I try binding like this, it does not works:
<input class="sometextbox">
<button type="button" data-bind="click: $root.someFunction.bind($root,$(this).siblings('input').val())"> Search!
</button>
I get the error at $(this), JavaScript runtime error: Object doesn't support property or method 'siblings'
$element gives you access to the current element in a Knockout binding.
<input class="sometextbox">
<button type="button" data-bind="click: $root.someFunction.bind($root, $($element).siblings('input').val())"> Search! </button>
Note that using jquery in a Knockout binding is not a common approach.
Your code isn't really making correct use of knockout. Using it to add click events when (as your fiddle example shows) a regular in-line event definition works fine, but ignoring the ability of knockout to bind that textbox to some variable in your program seems like you're getting things backwards.
Something more like this is how I think knockout was intended to be use:
<script>
ko.applyBindings(model);
function myModel(){
this.myInput = ko.observable('some default value');
}
function myClick(){
alert(model.myInput());
}
</script>
<input class="textbox" data-bind="value: myTextArea">
<button data-bind="click: myClick">Go</button>

ng-click doesn't take parameters from the DOM

I have the following code:
<input id="id">
<button data-action="bea" ng-click="Create($('#id1')[0].value);" class="btn">Insert ID</button>
<button data-action="bea" ng-click="Create($('#id2')[0].value);" class="btn">Insert ID</button>
In the JS I have:
$scope.Create = function (id){
if (id === undefined) {
$scope.data = "You must specify an id";
} else {
$scope.data = data;
console.log(data);
});
}
};
When the call gets into the Create function the value of the id is undefined.
If I add the following line at the beginging of the Create function everything works ok:
id = $('#id')[0].value;
If I send a constant value it works:
<button data-action="bea" ng-click="Create('SomeID');" class="btn">Insert ID</button>
Why is this happening and how can I do that without putting the line of value into the method?
Thanks
This is just an extension of comments and other answers, You could achieve this in many ways using angular, one simple example could be:-
<!-- Add a controller -->
<div ng-controller="MainCtrl">
<!-- Give a model binding to your text input -->
<input ng-model="userEntry" type="text"/>
<!-- ng-click pass which ever argument you need to pass, provided it is an expression that can be evaluated against the scope or any constants -->
<button data-action="bea" ng-click="Create(userEntry);" class="btn">Insert ID</button>
<!-- Some simple data binding using interpolation -->
{{data}}
<!-- Just for demo on repeater on a list of items on the scope -->
<div ng-repeat="item in items track by $index">{{item}}</div>
</div>
Example Demo
My 2 cents on the lines of what were originally trying to do:-
Use angular bindings instead of accessing DOM directly for getting the data, it really helps you deal with just the data without worrying about how to access or render it in DOM. If you think you need to access DOM for implementing business logic re-think on the design, if you really need to do it, do it in a directive. Angular is very opinionated on the design and when where you do DOM access.
ng-model
ng-binding
controller
all about ngmodel controller
This is not the way you should do in AngularJS. You should really think in Angular if you want to use AngularJS. Refer this post ("Thinking in AngularJS" if I have a jQuery background?)
All DOM manipulation should be done in Directive. Refer this page that I found really clear.
(http://ng-learn.org/2014/01/Dom-Manipulations/)
My guess is that $ is not bound to the jQuery function when the ng-click value is evaluated, because it is not exposed in the Angular scope.
Solutions to adress this:
expose the jQuery function in scope somewhere, e.g $scope.$ = $; in a controller.
make the Create function parameterless as you suggested, with a var id = $('#id')[0].value; at the beginning
my favorite : avoid using jQuery. If you put some data in the #id element, there's probably a more natural and AngularJS-idiomatic way of retrieving it than querying the DOM (e.g an Angular service).
In particular, if the element you're targeting is an <input> element, then use the ngModel directive to link the value to a $scopeproperty that will be accessible in the controller :
<input ng-model="inputData"/>
The JavaScript you are trying to pass as a parameter of the create function is not available in the scope of the Create function.
Try to target the element a different way.
Does that help?

Change text input value with jQuery - Chrome extension

I am trying to change input value in particular web site from chrome extension. In order to do that I am using jQuery in my content script. It works in most of the cases, but I didn't manage to change value of the input when it is part of AngularJS view. I found the same problem when I use let say kendoUI. I am trying to set the value calling $('element').val('value') and then try to call blur and change event, but without any success.
I went through may be 99% of the posts related to this topic, but still can't find working solution.
You just need to Call $scope.apply() in order to let angular know about updating the bindings. This is mainly because by default, angular doesn't know anything about the changes you are making in jQuery.
Below is a sample code, and here is a jsFiddle. Hope this helps.
app.controller('testCtrl', ['$scope', function ($scope) {
$scope.changeValue = function() {
$('#test').val("new Value");
$scope.apply();
}
<div class="form-inline">
<input type="text" id="test" value="test">
<input type="submit" value="submit" ng-click="changeValue()">
</div>

angular-ui: datepicker seems to hang angularjs when showing button

I have this piece of html code in my application (the ng-app and ng-controller values are defined before):
<div>
<label for="projectSearchDateFrom"><%= Res("Projects.Search.From")%></label>
<input id="projectSearchDateFrom" type="text" ng-model="startDate" ui-date="dateOptions"/>
<img ng-show="hasStartDate()" ng-click="clearStartDate()" src="/_Layouts/ClientPortal/Images/layout/TA/delete-small.png" alt="<%= Res("ToolbarDialog.Clear")%> <%= Res("Projects.Search.From")%>" title="<%= Res("ToolbarDialog.Clear")%>" />
</div>
My AngularJS controller looks like this:
function ProjectSearchCtrl($scope) {
$scope.startDate = '';
$scope.hasStartDate = function () {
return $scope.startDate != '';
};
$scope.clearStartDate = function () {
$scope.startDate = '';
};
$scope.dateOptions = {
dateFormat: "yy-mm-dd",
showOn: "focus"
};
}
This works perfectly: I have a datepicker set up correctly thanks to AngularUI, the AngularJS binding works...
But if I change the showOn value to "button" or "both" (the two possible options which will actually show the datepicker button), everything after the input (containing the ui-date attribute) stops working: ng-show, ng-click... The controller doesn't even get called.
Versions (all is up-to-date):
jQuery 1.7.2
angularJS 1.0.0
angularUI 0.1.0
Chrome 20
Please take a look at this line in the Select2 directive. This is a note to ANYONE writing a directive / implementing a plugin in AngularJS (not just AngularUI):
Any plugin that injects a new DOM element immediately after the linked element runs the risk of disrupting the compiler. The reason is because the way AngularJS works, it caches the index of each DOM element at compile time, and then makes a second pass upon linking. When you inject new DOM, you offset the index of all siblings immediately after the directive.
For this reason, I've been forced to wrap both TinyMCE and Select2 in a setTimeout so that the DOM is injected after the linking is done. Note that I don't bother using $timeout because I really don't need/want $apply() to fire just to turn on the plugin, as there are already callbacks in place that do this when the plugin changes the data.
I'll look into making sure this is uniform across AngularUI. Unfortunately, there appears to be no elegant solution to this problem in AngularJS at this time, however it's a problem I've been thinking about for some time and am constantly looking for a better solution towards.
Read this Google Groups post for more information about compiling vs linking: https://groups.google.com/forum/?fromgroups#!searchin/angular/compile$20link/angular/RuWn5W3Q5I0/KJhcQJ_RNsIJ
You can also open a bug ticket on the AngularUI project in the future.
As suggested by Pete BD in his comment on the question, there is some kind of bug/unwanted behaviour in the way that jQueryUI and angularJS interact. A workaround is to wrap the input control in a div.
<div class="date">
<label for="projectSearchDateFrom"><%= Res("Projects.Search.From")%></label>
<div>
<input id="projectSearchDateFrom" type="text" ng-model="startDate" ui-date="dateOptions"/>
</div>
<img class="clear" ng-show="hasStartDate()" ng-click="clearStartDate()" src="/_Layouts/ClientPortal/Images/layout/TA/delete-small.png" alt="<%= Res("ToolbarDialog.Clear")%> <%= Res("Projects.Search.From")%>" title="<%= Res("ToolbarDialog.Clear")%>" />
</div>
Now I can use showOn "both" or "button".
This is fixed in the latest release!

Categories

Resources