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.
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 a following code
<div class="btn btn-success form-control ng-binding" ng-click="test(uid)">
First
</div>
<div class="btn btn-success form-control ng-binding" ng-click="test(uid)">
Second
</div>
<div class="btn btn-success form-control ng-binding" ng-click="test(uid)">
Third
</div>
How do i iterate elements based on ng-click to check for a specific text value(First or Second or Third) in Protractor?I tried the following but i get undefined for uids.length. What is wrong here?
var uids = element.all(by.css('[ng-click="test(uid)"]'));
for(var i=0;i<uids.length;i++)
console.log(uids.get(i).getText());
The problem is element.all() returns an ElementArrayFinder rather than a simple array. If you look at the linked documentation you'll see some functions that allow you to easily interact that data structure. I believe you want to use the each() function like so:
element.all(by.css('[ng-click="test(uid)"]')).each(function(element, index) {
element.getText().then(function (text) {
console.log(text);
});
});
Also worth noting that the getText() function, like nearly all functions in Protractor, returns a promise and therefore needs to be resolved before you can access the value you really want.
My Plunkr: http://plnkr.co/edit/4MkenJPczFbxy5aoillL?p=preview
<body ng-controller="mainCtrl as main">
<h1>Hello Plunker!</h1>
<p>Button should not be disabled:</p>
<div ng-init="main.btnDisabled = false">
<button ng-model="main.my_button"
ng-class="{ 'btn-success' : !tc.switching, 'btn-disabled' : tc.switching }"
disabled="main.btnDisabled"
type="button"
class="btn btn-info btn-sm switch-btn">My Button</button>
</div>
Angular
angular.module('app').controller('mainCtrl', function($scope) {
vm = this;
vm.btnDisabled = false;
});
I found this answer here, but it didn't work in my example.
The button is disabled because there is disabled attribute. This is enough for browser to know that element must be inactive. The value for disabled attribute doesn't matter, it can be anything.
This is exactly the reason why Angular provides ngDisabled directive, which adds disabled attibute when expression evaluates to true, and removes when it's false.
In your case you should use
<button ng-model="main.my_button"
ng-class="{ 'btn-success' : !tc.switching, 'btn-disabled' : tc.switching }"
ng-disabled="main.btnDisabled"
type="button"
class="btn btn-info btn-sm switch-btn">My Button</button>
There are a few problems that I see here.
First, change disabled to ng-disabled.
Second, when you click the button nothing will change/happen. Instead of putting that functionality into your ng-class, use something like ng-click to change the state.
This isn't contributing to your problem but make sure that you include $scope before passing it into your controller function.
Speaking of $scope, the plunker would be a bit easier to read if you put something on the scope instead of using a controller alias. No problem with that, it just might help you and other people debug your code.
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
I use AngularJS in my single-page application. Somewhere I have defined a button like this
<button class="btn btn-success" onclick="doSeekTo({{todo.position}});doPlay();">
This button, when clicked, invokes the javascript function with the given parameter in double curly braces, as usual with AngularJS.
This all works well in IE9, but when looking at the error console, it says “Expected identifier, string or number” at the position of my curly braces.
How to get rid of this error? It makes me feel uncomfortable.
In Angular, you're not supposed to use the built in onclick event, but rather Angular's ng-click event. That way you can write
ng-click="doSeekTo(todo.position);doPlay()"
IE9 is parsing the HTML before your angularjs code modifies it. Maybe some indirection like this would help ...
<button class="btn btn-success" paramvalue="{{todo.position}}" onclick="doSeekTo(this.paramvalue);doPlay();">
Another option is to enclose the {{}} in single quotes such that IE interprets it as a string:
<button class="btn btn-success"> onclick="doSeekTo('{{todo.position}}');doPlay();">