I'm having what seems to be a rather simple problem in my first full Angular application. I have some code:
<div class="button-bar bar-dark" ng-controller="FeedController">
<a class="button" onclick="console.log('..');" ng-click="console.log('...');">Click Me</a>
</div>
At first I thought I was having an issue with $scope, and EVERY single question related to ng-click I found on SO about it not firing leads back to that, but as you can see from the above code (after I changed from my function to a simple console.log), my issue is simpler - ng-click just doesn't do anything. There's no error. The onclick fires, but ng-click does not.
What's weirdest is that in that same page, I have the following that DOES work:
<div class="list" id="rssnews" ng-controller="FeedController">
<a ng-click="doSomething('{{entry.link}}')">
<span ng-bind-html="entry.content"></span></a>
</div>
Try calling functions in both events, the following works for me:
<a class="button" onclick="nativeFn()" ng-click="ngFn()">Click Me</a>
Declare the one function in the same file
function nativeFn() {
alert("nativeFn is triggered!");
};
and the other one in your controller
function MyCtrl($scope) {
$scope.ngFn = function () {
alert("ngFn is triggered!");
};
}
Related
ng-if is not working when I change the values through simple javascript function.My function is getting called but the changes in values cannot be seen in view. Please refer below code.
HTML
<div id="span" ng-app='MyModule' ng-cloak ng-controller="MyController">
<div ng-if="!bool">
This is for true
</div>
<div ng-if="bool">
This is False
</div>
{{bool}}
<br>
<input type="submit" ng-click = "myfunction('test')" value="ng-if button">
</div>
<input type="submit" onClick = "check1()" value="simple JS button">
JS
angular.module('MyModule', [])
.controller('MyController', function ($scope) {
$scope.bool = true;
$scope.myfunction = function (data) {
$scope.bool = !$scope.bool;
};
});
function check1() {
angular.element(document.getElementById('span')).scope().myfunction('test');
}
When I use ng-click button it changes value of bool changes, but same doesn't happens with simple JS button . Actually I am implementing Angular in a page that already uses jQuery, so I need to use simple JS button.
JS Fiddle : JS Fiddle
At first, ng-click is able to parse an angular expression.
Second, it handles the reference to the current scope and performs a call to $scope.$apply to notify any watchers to update. If you would add a call to angular.element(document.getElementById('span')).scope().$apply() in your function, it should work as expected.
Use $scope.apply . This is because angulars digest cycle will not know if your value changes outside of its scope like in a simple JS function.
I have codes :
HTML :
<div class="modal-footer" >
<button type="button" class="btn btn-sm btn-default" id="mybutton" style="background-color: #367E2D; color:white; opacity: 1" onclick="chooseme();">OK</button>
</div>
Javascript :
('#mybutton').click(chooseme('123'));
Purpose :
I want to change onClick event from chooseme() to chooseme('123') using Javascript
And the result of the code above is :
chooseme('123') executed immediately (not when the button clicked)
Question is : Anyone can explain what's wrong with my code? and what is
the correct implementation to reach the purpose above?
I assume from the syntax that you're using jQuery. When binding events to named functions in JS, you need to pass the function itself to the callback. With your current syntax, you're passing the return value from chooseme() to the click handler. As a result, the function is called immediately on page load.
Wrap the hander inside an anonymous function, and you're good to go:
$('#mybutton').on('click', function() { chooseme('123') });
I am working with Onsen UI (angularjs) + Cordova and I have this problem:
I have a button that is not working right now, but this button was working sometime ago. Now I cannot even get click event of the button.
Does somebody know what is the problem?
HTML:
<ons-list id="list-actions" style="border-top: none"><ons-list-item style="line-height: 1; padding: 0;">
<ons-row class="action">
<ons-col class="bt-pres action-col col {{interaction[0].present}}">
<div class="action-icon"><ons-icon icon="ion-fireball"></ons-icon></div>
<div class="action-label">Press</div>
</ons-col>
Javascript:
//not working
$(document).on("click",".bt-pres",function(){
alert("clicked");
Thanks for all your replies. Looking the code again and over again, my bad was I had twice codes like $(document).on('click', elem, func) and it was in conflict. Then I changed this to use angular ngclick function inside controller. This worked like a charm. Thank you all
First of all alert() is not working in neither ripple nor device (as per my knowledge). If you want to trigger the function i suggest ng-click()
example
HTML
<div ng-controller="LoginController">
<ons-button ng-click="Login()">Login</ons-button>
</div>
JS
.controller('LoginController', function () {
$scope.Login = function () {
console.log("triggered");
}
}
in your case try the bellow code
$(document).on("click","div.action-label",function(){
console.log("triggered");
}
I am learning AngularJS. I have some article tag and on clicking on a button each article page is showed without any page refresh. This is one page website. What I want is that when article id "showSelector" is loaded I want to call myFunction() and in this function I want to show an alert. But the alert is not showing.
How can I do that?
<article id="showSelector" class="panel" ng-controller="CinemaCtrl" onload="myFunction()">
<header>
<a ng-click="back()" class="icon fa-arrow-circle-left"></a><h2>Shows in {{getSelectedCinema()}}</h2>
</header>
<p>
These shows are played in our single room theatre. Select one to reserce a ticket for it.
</p>
<section>
<div class="row">
<div class="4u" ng-repeat="show in shows">
<div class="movieCard">
<a ng-click="selectShow(show)"></a>
<h3>{{show.nameOfShow}}</h3>
<h4>{{show.timeOfShow | date:'MMM d'}}</h4>
<h4>{{show.timeOfShow | date:'HH:mm'}}</h4>
<p>Free seats: {{show.reservations | freeSeatFilter}}</p>
</div>
</div>
</div>
</section>
<script>
function myFunction() {
alert("Page is loaded");
};
</script>
</article>
You should call this function from the controller.
angular.module('App', [])
.controller('CinemaCtrl', ['$scope', function($scope) {
myFunction();
}]);
Even with normal javascript/html your function won't run on page load as all your are doing is defining the function, you never call it. This is really nothing to do with angular, but since you're using angular the above would be the "angular way" to invoke the function.
Obviously better still declare the function in the controller too.
Edit: Actually I see your "onload" - that won't get called as angular injects the HTML into the DOM. The html is never "loaded" (or the page is only loaded once).
Instead of using onload, use Angular's ng-init.
<article id="showSelector" ng-controller="CinemaCtrl" ng-init="myFunction()">
Note: This requires that myFunction is a property of the CinemaCtrl scope.
<section ng-controller="testController as ctrl" class="test_cls" data-ng-init="fn_load()">
$scope.fn_load = function () {
console.log("page load")
};
It's not the angular way, remove the function from html body and use it in controller, or use
angular.element(document).ready
More details are available here: https://stackoverflow.com/a/18646795/4301583
you can also use the below code.
function activateController(){
console.log('HELLO WORLD');
}
$scope.$on('$viewContentLoaded', function ($evt, data) {
activateController();
});
you can use it directly with $scope instance
$scope.init=function()
{
console.log("entered");
data={};
/*do whatever you want such as initialising scope variable,
using $http instance etcc..*/
}
//simple call init function on controller
$scope.init();
var someVr= element[0].querySelector('#showSelector');
myfunction(){
alert("hi");
}
angular.element(someVr).ready(function () {
myfunction();
});
This will do the job.
I'm a little puzzled by some code I plunked together that doesn't behave quite as I'd expect.
I'm sure I'm doing something wrong (and given the late hour here, it might be something simple), but I'm looking for some clarity on why this happens.
I'm using:
jQuery 1.10.2
Knockout 2.3.0
Bootstrap 3.0.3
The Problem
I define a function in my ViewModel, which sets an observable to a certain value.
This is not called from anywhere else in my code.
I define a data-bind="click: AddAnnouncement" binding on a button that's part of a button group.
When ko.applyBindings(vm) is called, the AddAnnouncement function fires, giving me an undesired result long before I click on anything.
The Code in Question
Can be found in a JSFiddle at: http://jsfiddle.net/SeanKilleen/v8ReS/.
Essentially, I have the following JavaScript code:
var MyNamespace = MyNamespace || {
ViewModel: function(){
'use strict';
var self = this;
self.AddingAnnouncement = ko.observable(false);
self.AddAnnouncement = function(){
self.AddingAnnouncement(true);
};
self.Start = function(){
self.AddingAnnouncement(false);
};
self.Start();
}
};
var vm;
$(document).ready(function(){
'use strict';
vm = new MyNamespace.ViewModel();
ko.applyBindings(vm);
//do something with jQuery? Bind a VM?
});
My binding code is also pretty elementary (I thought):
<div class="container">
<div class="row">
<div class="btn-group">
<button type="button" class="btn btn-default"><abbr Title="Announcement" data-bind="click: AddAnnouncement()">A</abbr>
</button>
</div>
</div>
<div class="row" data-bind="visible: AddingAnnouncement() == true">
<h1>Add a new announcement</h1>
</div>
</div>
What I think it's doing
I think the code in question is doing the following:
Defining a namespace called MyNamespace (albeit probably not in the best way; this may be part of the problem?)
Defining a ViewModel object inside the namespace
Giving the ViewModel object an observable called AddingAnnouncment and a function called AddAnnouncement, which sets AddingAnnouncement to true.
Defines a Start method which ensures that AddingAnnouncement is set to false by default;
Calls the Start method as the last step in its initialization.
What am I Missing Here?
I think I'm not grasping some standard behavior of JavaScript or something about the way knockout binds models, but it seems like when applying the bindings, knockout executes all of the functions, even for the click bindings. However, that doesn't make sense to me and so I'm betting I'm wrong.
Someone enlighten me? Thanks!
Whooops! The answer to that question turned out to be right under my nose; indeed, all I had to do was write that entire darn question before I saw it. :)
The problem is with my binding:
<button type="button" class="btn btn-default"><abbr Title="Announcement" data-bind="click: AddAnnouncement()">A</abbr>
Note a very important distinction: AddAnnouncement(). The () matters quite a bit in this case.
When knockout assigns its binding, it does so by directly referencing what you enter. Since I entered AddAnnouncement(), it assigned the binding to the output of the function that had been run once, rather than the function itself which would be executed at a later time.
The best way to do it would have been to use AddAnnouncment, without paranetheses, like this:
<button type="button" class="btn btn-default"><abbr Title="Announcement" data-bind="click: AddAnnouncement">A</abbr>
This does not execute the function upon applying bindings.
While I forgot to avoid such a simple mistake, I hope it saves someone else time in the future. The working JSFiddle can be found at http://jsfiddle.net/SeanKilleen/v8ReS/4/.
We usually confuse when to use parentheses () when we bind View with ViewModel.
As when you bind AddAnnouncement function, you directly bind with function call like AddAnnouncement(). That why the AddAnnouncement function call when you bind using ko.applyBindings even though we didn't click the button, the function call already fire.
<div class="row">
<div class="btn-group">
<button type="button" class="btn btn-default">
<abbr Title="Announcement" data-bind="click: AddAnnouncement()">
A
</abbr>
</button>
</div>
</div>
so we change as below
<div class="row">
<div class="btn-group">
<button type="button" class="btn btn-default">
<abbr Title="Announcement" data-bind="click: AddAnnouncement">
A
</abbr>
</button>
</div>
</div>
working jsfiddle