ng-click not firing in AngularJS while onclick does - javascript

I am trying to use AngularJS in my application and have been successful to some extent.
I am able to fetch data and display it to the user. And I have a button in ng-repeat via which I want to post DELETE request. Below is my code which does it.
<div class="navbar-collapse collapse">
<table class="table table-striped" ng-controller="FetchViewData">
<tr>
<td>Name</td>
<td>ID</td>
<td>Department</td>
<td></td>
</tr>
<tr ng-repeat="d in viewData">
<td>{{d.EmployeeName}}</td>
<td>{{d.EmployeeID}}</td>
<td>{{d.EmployeeDepartment}}</td>
<td>
<button class="trashButton" type="button"
name="view:_id1:_id2:_id14:_id24:btnDelete"
id="view:_id1:_id2:_id14:_id24:btnDelete"
ng-click="deleteRecord('{{d['#link'].href}}')">
<img src="/trashicon.gif"></button>
</td>
</tr>
</table>
</div>
This is the FetchViewData function which fetches the information and displays it to the user.
function FetchViewData($scope, $http) {
var test_link = "<MY LINK>";
$http.get(test_link).success( function(data) {
$scope.viewData = data;
});
}
The data is fetched and properly displayed.
But the code in ng-click="deleteRecord('{{d['#link'].href}}')" does not fire when delete button is clicked. In Google Chrome's developer tools I can see valid values are generated for code {{d['#link'].href}} but the code deleteRecord does not get fired. From this question I tried removing the braces and writing only d['#link'].href but it didn't work for me.
When I replace ng-click with onclick the deleteRecord function gets fired.
function deleteRecord(docURL) {
console.log(docURL);
$http.delete(docURL);
}
But then I receive the below error.
Uncaught ReferenceError: $http is not defined
deleteRecord
onclick
I am using jQuery 1.10.2 and AngularJS v1.0.8.

FetchViewData here is a controller, and in your html, where you have ng-controller="FetchViewData", you are telling it to look within that controller's scope for any angular methods and variables.
That means, if you want to call a method on click, it needs to be calling something attached to your controller's scope.
function FetchViewData($scope, $http) {
var test_link = "<MY LINK>";
$http.get(test_link).success( function(data) {
$scope.viewData = data;
});
$scope.deleteRecord = function(docURL) {
console.log(docURL);
$http.delete(docURL);
}
}
Here, the function exists on the scope, and any html that is inside your FetchViewData Controller has access to that scope, and you should be able to call your methods.
It's working when you use on-click because your function exists in the global namespace, which is where on-click is going to look. Angular is very heavily reliant on scoping to keep your namespaces clean, there's lots of info here: https://github.com/angular/angular.js/wiki/Understanding-Scopes

INSTEAD of this
ng-click="deleteRecord('{{d['#link'].href}}')"
TRY this
ng-click="deleteRecord(d['#link'].href)"
You don't need to use curly brackets ({{}}) in the ng-click
ENJOY...

function deleteRecord(docURL) {
console.log(docURL);
$http.delete(docURL);
}
It should be
$scope.deleteRecord = function (docURL) {
console.log(docURL);
$http.delete(docURL);
}
EDIT:
change something in html and controller ....
SEE WORKING DEMO

The deleteRecord method should be assigned in the current and correct scope
$scope.deleteRecord = function(){
....

Another possibility for why ng-click does not fire, is that you are apply a CSS style of pointer-events:none; to the element. I discovered that Bootstrap's form-control-feedback class applies that style. So, even though it raises the z-index by 2 so that the element is in front for clicking, it disables mouse-clicks!
So be careful how your frameworks interact.

As mentioned, the function should be created inside the scope:
$scope.deleteRecord = function (docURL) {
console.log(docURL);
$http.delete(docURL);
}
To use the function, first drop the "{{ }}" since you are using it from inside an ng-repeat. Another issue is the use of apostrophe in your code, you have two pairs one inside the other... well I am sure you get the problem with that.
Use the function like so:
ng-click="deleteRecord(d['#link'].href)"
Best of luck !

If you want to use as a submit button the set the type to 'submit' as:
<button type="submit" ...

Related

How to stop AngularJS from Binding in Rows

I am using Angularjs 1.5.3 I have 2 services one service calls Area names, the other calls the details for the Area.
So in my code, I call the first service to get the Area, then I set the ng-init to call the details. This works fine, however angular keeps only the first value for all the rows.
Here is the code;
<tbody data-ng-repeat="area in vm.Areas" ng-init='vm.getDetails(area)'>
<tr>
<td class="text-bold">{{area}}</td>
<td>{{vm.AreaDetails.Employees}}</td>
<td>{{vm.AreaDetails.Hours}}</td>
<td>{{vm.AreaDetails.Sales}}</td>
</tr>
</tbody>
Any ideas on fixing this?
Thanks
You should avoid using ng-init for this. It's an abuse of ng-init and decrease your performance drastically. See: ngInit. Try to get your details before you start rendering eg (pseydo):
vm.areas = vm.areas.map(function(area) {
return area.details = service.getDetails(area);
}
#TJ answer is right on the technical part however i think you have a design problem in your code.
If you want to load area and their details you should load all of them in one go.
Instead you'll load them one by one there.
So let's say you have 10 Area and you're Detail service load data from (i suppose) the server : that makes 11 requests : 1 for all area, 10 for details of each area.
So just load all the whole thing in one call to your service (and presumably the server) and perform a simple ng-repeat.
You can simply have the controller iterate over the areas and call getDetails for each of them and append the detail to the respective area when they arrive.
The bindings will be along:
<tbody data-ng-repeat="area in vm.Areas">
<tr>
<td class="text-bold">{{area}}</td>
<td>{{area.details.Employees}}</td>
<td>{{area.details.Hours}}</td>
<td>{{area.details.Sales}}</td>
</tr>
</tbody>
The bindings will be updated when the data arrive.
Or you can use a directive with isolated scope, something like the following:
angular.module('yourModule').directive('areaInfo', function() {
return {
scope: {
area: '=areaInfo'
},
require: "yourController", // conroller where getDetails is defined
templateUrl: "area-info.html",
link: function(scope, element, attrs, ctrl) {
scope.areaDetails = ctrl.getDetails(scope.area);
}
}
});
<script type="text/ng-template" id="area-info.html">
<tr>
<td class="text-bold">{{area}}</td>
<td>{{areaDetails.Employees}}</td>
<td>{{areaDetails.Hours}}</td>
<td>{{areaDetails.Sales}}</td>
</tr>
</script>
<tbody data-ng-repeat="area in vm.Areas" area-info="area"></tbody>
You can even move the getDetails method to the directive itself.

Conditionally Alter link in button in Angular

I am trying to figure out a simple way to swap a link in a button in angular js, I have properties available in the scope that I can use, but I am not sure how to implement. The link I am trying to alter is in the 'onClick' attribute in the button. Thanks again in advance, here is my code:
<div class="instructions-button">
<button
type="button"
class="halo-modal-action-button external-instructions"
onClick="window.open('https://mysite/foo');"
window="new"
ng-disabled=""
ng-click=""
data-bs-enabled=""
>Instructions</button>
</div>
I am trying to make a simple conditional to show either:
'mysite/foo || mysite/bar'
but am not sure how to make it work.
Don't use onClick event on the button, although it might feel weird to you, since you are coming from vanilla JS, you should use ng-click.
<button
class="halo-modal-action-button external-instructions"
ng-disabled=""
ng-click="openWindow()"
data-bs-enabled=""
>Instructions</button>
and inside controller
$scope.openWindow = function(){
if ( condition ) {
open('http:foo.bar')
} else {
open('http:bar.foo')
}
}
Two simple ways to do this.
1) Two buttons and show one conditionally with ng-show.
<button ... ng-show="conditionShowFooTrue" >
<button ... ng-show="conditionShowBarTrue" >
2) Use ng-click to call a scope function to conditionally sets the url as the other answers have suggested.
If you're using routes, you can just use ng-click like #Akxe said, and with the $location service in your controller, do:
$scope.changeLocation = function(){
if(condition)
{
$location.path('/foo');
} else
{
$location.path('/bar');
}
};
I think that would be the Angular way to do this.

AngularJS $scope variable does not go into view

I have a simple boolean variable that switches a DIV to be hidden at startup and then shown after an action until the end of the application. But it does not switch - the DIV is always hidden. Please help, what is wrong in the code below:
<div class="right" ng-controller="EmployeeDetailsCtrl" ng-show={{showEmployeeDetails}}>
<p>{{employee.name}} {{employee.surname}}</p>
</div>
inside EmployeeDetailsCtrl controller:
$scope.$on('showEmployee', function (event, data) {
$scope.showEmployeeDetails = true;
$scope.employee = data;
});
$scope.showEmployeeDetails = false;
BTW, the $scope.employee variable updates correctly after the event is triggered, so I'm really stuck what's going on here.
Remove the {{}} from your ng-show, like so:
<div class="right" ng-controller="EmployeeDetailsCtrl" ng-show="showEmployeeDetails">
<p>{{employee.name}} {{employee.surname}}</p>
</div>
When you're using ng-show you're binding to an expression, not a string, so just use:
ng-show="showEmployeeDetails". That's why you can do more complex stuff like ng-show="1 + 1 === 2".
If that still doesn't cut it, it could be a scoping issue with primitives being assigned to a child scope and not seen up the parent scope. It doesn't look like it from the code you showed but perhaps it's simplified for this question, you never know.

get the text of div using angularjs

i want to get the text of div using angularjs . I have this code
<div ng-click="update()" id="myform.value">Here </div>
where as my controller is something like this
var myapp= angular.module("myapp",[]);
myapp.controller("HelloController",function($scope,$http){
$scope.myform ={};
function update()
{
// If i have a textbox i can get its value from below alert
alert($scope.myform.value);
}
});
Can anyone also recommand me any good link for angularjs . I dont find angularjs reference as a learning source .
You should send the click event in the function, your html code should be :
<div ng-click="update($event)" id="myform.value">Here </div>
And your update function should have the event parameter which you'll get the div element from and then get the text from the element like this :
function update(event)
{
alert(event.target.innerHTML);
}
i just thought i put together a proper answer for everybody looking into this question later.
Whenever you do have the desire to change dom elements in angular you need to make a step back and think once more what exactly you want to achieve. Chances are you are doing something wring (unless you are in a link function there you should handle exactly that).
So where is the value comming, it should not come from the dom itself, it should be within your controller and brought into the dom with a ng-bind or {{ }} expression like:
<div>{{ likeText }}</div>
In the controller now you can change the text as needed by doing:
$scope.likeText = 'Like';
$scope.update = function() {
$scope.likeText = 'dislike';
}
For angular tutorials there is a good resource here -> http://angular.codeschool.com/
Redefine your function as
$scope.update = function() {
alert($scope.myform.value);
}
A better way to do it would be to use ng-model
https://docs.angularjs.org/api/ng/directive/ngModel
Check the example, these docs can be a bit wordy

Angularjs binding not working on array of complex object

Given this controller:
angular.module("upload.app").controller("upload",[upload]);
function upload(){
var me = this;
me.uploadList = [{Name: "Test Upload",
Id: 1,
NewFiles: []
}];
me.selectedUpload = me.uploadList[0];
me.setSelected = function(upload) {
me.selectedUpload = upload;
}
...
me.addFilesToUpload = function(element){
me.selectedUpload.NewFiles = element.files;
}
and this html:
<div ng-controller="upload as vm">
<input id="filechooser" type="file" multiple onchange="angular.element(this).scope().vm.addFilesToUpload(this)" />
<table>
<tbody>
<tr ng-repeat="up in vm.uploadList" ng-click="vm.setSelected(up)">
<td>{{up.Name}}<br />{{up.NewFiles.length}}</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr ng-repeat="file in vm.selectedUpload.NewFiles">
<td>{{file.name}}</td>
</tr>
</tbody>
</table>
</div>
I would expect that when the input onchange event calls addFilesToUpload() and the files are then added to the NewFiles property, that Angularjs would automatically update the view ... in this case, {{up.NewFiles.length}} value in the first table and the second table that lists the files.
However, nothing is being updated until I click on my row in the first table which, as you can see, fires the setSelected function on my controller.
How can I get Angular to refresh when the NewFiles property is changed as well?
Sorry, just fixed the fiddle -- forgot to save it originally
See this jsfiddle. Begin by clicking on the Test Upload. Now select files. Nothing happens. Click again on Test Upload and you'll see all the bindings refreshed.
Use $apply (DEMO):
$scope.$apply(function() {
$scope.selectedUpload.NewFiles = element.files;
});
This is usually done by angular but because you are using the native js event onchange you have to wrap it in an $apply callback yourself.
There is no default binding provided by angular to input type=file https://github.com/angular/angular.js/issues/1375, so you'll probably need to create your own directive or you can use angular-file-upload library.
Check out this answer from stackoverflow.
The problem with your updated fiddle is mainly this line
$scope.selectedUpload = null;
The moment you have selected the files and invoke the callback addFilesToUpload(), and assign the selected files to $scope.selectedUpload.NewFiles = element.files; then you'll definitely get an error:
Uncaught TypeError: Cannot set property 'NewFiles' of null
Simply change it back to your original code: $scope.selectedUpload = $scope.uploadList[0];
The next problem would be to update the current selected upload list, simply use $scope.$apply(), because you are using a native event onchange to update the $scope. Your callback should look this:
$scope.addFilesToUpload = function(element){
$scope.$apply(function() {
$scope.selectedUpload.NewFiles = element.files;
});
}
Check this updated fiddle.

Categories