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
Related
I am working on a weather page for myself (and maybe others in the future) and having an issue with a button that will show and hide weather alerts. You can view the page to see what I'm trying to do. (Sorry, I'm picking on FL, but they have a lot of alerts right now).
Page Source
JS Source
I have my alerts coming into an array and for each item, I need a button that will show and hide the alerts. My page source contains:
<div data-bind="foreach: alertsViewModel.features">
<div class="col-12">
<div class="alert alert-danger" role="alert">
<p>
<strong data-bind="text: properties.headline"></strong>
<button type="button" class="btn btn-link" data-bind="click: $root.showHideAlert">Show</button>
</p>
<div data-bind="attr: {id: properties.id}" style="display: none;">
<p data-bind="lineBreaks: properties.description"></p>
<p><strong>Instructions</strong></p>
<p data-bind="lineBreaks: properties.instruction"></p>
</div>
</div>
</div>
</div>
And my ViewModel looks like:
// ==================
// Alerts View Model
// ==================
var alertsViewModel = {
features: ko.observableArray([]),
hwoUrl: ko.observable(""),
hwoText: ko.observable(""),
showHideAlert: function(data, event){
alert('you clicked');
/*$('#hwo').toggle('slow',function(){
if ($('#showHwo').text() == "Show")
{
$('#showHwo').text("Hide");
}
else
{
$('#showHwo').text("Show");
}
});*/
}
};
ko.applyBindings(weatherViewModel, document.getElementById('weather-alerts'));
I have tried a few different methods and I can't get anything to work. (Thus the commented code and the alert). Which is strange, since I have done this a few times in the past with no issues. I'm sure it's something simple I missed. Any help would be appreciated.
Could it perhaps be because you used the weatherViewModel in your call to ko.applyBindings instead of alertsViewModel?
I think the $root in the button's bindings refers to weatherViewModel since that's the VM applied by ko.
Perhaps try changing the location of the function or simply use alertViewModel instead.
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'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!");
};
}
I wish the previous questions had answered this problem, but it seems like I'm facing something different here, unless I'm missing something..
I understand ng-repeat creates a child object and from that we can call things such {{note.id}}.
My problem is living in my attempt to pass that note.id to ng-click
Below the code with attempts and errors.
<div class="col-lg-3" ng-controller="mainCtrl">
<div class="list-group">
<a href="#notes/{{note.id}}" class="list-group-item" ng-repeat="note in notes" >
{{note.title}}
<button ng-click="deleteNote(note.id)" class="btn btn-danger" >x</button>
</a>
</div>
</div
Inspecting the elements we have
<a href="#notes/5" class="list-group-item ng-binding ng-scope" ng-repeat="note in notes">
hello update
<button ng-click="deleteNote(note.id)" class="btn btn-danger">x</button>
</a>
And in case I try something that would look more like the angularjs sintax
<button ng-click="deleteNote({{note.id}})" class="btn btn-danger" >x</button>
In that case my element inspection brings up the right id ...
<button ng-click="deleteNote(5)" class="btn btn-danger">x</button>
Bu I have an error
Error: [$parse:syntax] http://errors.angularjs.org/1.2.19/$parse/syntax?p0=note.id&p1=is%20unexpected%2C%20expecting%20%5B%3A%5D&p2=14&p3=deleteNote(%7B%7Bnote.id%7D%7D)&p4=note.id%7D%7D)
I could not tell what the error is from the message or the link it takes me to
Syntax Error: Token 'note.id' is at column {2} of the expression [{3}] starting at [{4}].
code for the controller
.controller('mainCtrl',['$scope', 'notesFactory', function($scope, notesService){
$scope.notes = notesService.notesObjectInService;
$scope.addNote = function(){
if ($scope.title === "" ) {
return;
}
notesService.create({
title: $scope.title
body:$scope.body
});
$scope.title= '';
$scope.body= '';
};
$scope.deleteNote = function(id) {
notesService.delete(id);
notesService.getAll();
};
}])
http://jsfiddle.net/p2t1waxp/2/
Your first attempt
<button ng-click="deleteNote(note.id)" class="btn btn-danger">x</button>
actually works, doesn't it?
It just doesn't render the id when you inspect it, but it process it right in the controller, as you can see in the console
I'm sorry but turns out that the standard way to do things as supposed works just fine. ng-click(note.id) ..
I had not implemented completely my function yet because I was debugging with Chrome tools Inspecting the element and I expected that the id element should come up in the inspection. Once it didn't as I showed in the code above I assumed it was wrong. But by finishing implementing the service and the back end it actually works just fine.
It's something I didn't know about the developer tools. What i still don't understand is why the id doesn't show up in the html inspection like href="#notes/{{note.id}}" ....I am assuming it has to do with the {{}} notation, but I'd have no precise answer for it. If someone can explain it'd help with my knowledge of angular and html as I'm new to programming.
Thanks and sorry for silly mistake.
I am using the following way to use $scope variable ({{func}}() in this case) as function name in ng-click.
<button type="button" ng-click="{{func}}()">Call {{func}}</button></pre>
This works in angularjs-1.2.0rc3. See working plunkr here
Any future version from > 1.2.0rc3 throw this error
What's changed? How can I use the above syntax in current angular version?
Ok first of all I do not recommend such a usage for ng-click because angularjs itself do not support this, but if you still want to use it such a way here is your solution...
<button type="button" ng-click="$eval(functionName)()">...</button>
where
$scope.f1 = function() {
...
};
//name of function as a string
$scope.functionName = "f1";
this is what your are looking for and here is your PLUNKER example...
All I did was append scope to both variables
<form name="angular" ng-controller="Ctrl">
<button type="button" ng-click="{{scope.func}}()">
Call {{func}}
</button>
<label>Status: {{scope.status}}</label>
http://jsfiddle.net/bebold/TmKLY/1/
I wouldn't advise going this route for dynamic variable change, a better choice would be to create a directive and do the binding within the template:
A great explanation can be found HERE.