AngularJS calling a function inside a controller with ng-click - angularjs

I've got a problem with getting my function inside my controller to work properly.
given the following partial:
<div ng-controller="KundeDetailCtrl"><table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>InstallationsID</th>
</tr>
</thead>
<tbody >
<tr data-ng-repeat="mandant in kunde.mandanten" ng-click="getMandant(mandant)" >
<td> {{mandant.name}}</td>
<td>{{mandant.id}}</td>
</tr>
</tbody>
</table></div>
I want to be able to click on one row and call the appropriate function in my controller:
var AppControllers = angular.module('AppControllers', []);
AppControllers.controller('KundeDetailCtrl', ['$scope', '$routeParams', 'Kunde',
function($scope, $routeParams, Kunde) {
$scope.kunde = Kunde.get({kundeId: $routeParams.kundeId}, function(kunde) {
});
$scope.getMandant = function(id){
for(var i= 0, l=$scope.kunde.mandanten.length; i<l; i++){
if($scope.kunde.mandanten[i].id == "id")
{
$scope.mandant = $scope.kunde.mandanten[i];
}
}
Location.href='index.html#/kunden/{{kunde._id}}/module'
};
}]);
Actually, I only want to know which row was clicked and hand the object of the clicked row to the next partial which is supposed to display some other data.
The ng-click does not seem to do anything at all. In the console I only see getMandant: null
Can anyone help me with this?

It seems you are comparing the id in the mandaten list to the string "id" rather than the object id:
if($scope.kunde.mandanten[i].id == "id")
You should also consider using === rather than ==, it is the preferred way to compare things in javascript.
It appears you are redirecting to another view in your angular application, any reason not to use the $location service?

Related

I am using MVC 4 and angularjs in this actually I want to call an angular js function on page load

i want to invoke angularjs function (DeptSpecific) on page load and am passing ID as the parameter which is hard coded. And that i am passing via ng-init="DeptSpecific('1')". I am learning angularjs please suggest me how to call a function and pass a parameter to it on page load without any click or anything just when a page load a function should be called. If you are thinking why i used ng-init ..there is no specific reason for this it might be wrong but it calls the function well i can see that in debugger (f12) but $scope.s i undefined even though there is a matched ID.
$scope.DeptSpecific = function (ID) {
var BelongsToThisDepartment = [];
$http.get('/Department/getDept').success(function (response) {
$scope.departments = $scope.$eval(response);
});
angular.forEach($scope.departments, function (item1) {
if (item1.ID == ID) {
BelongsToThisDepartment.push(item1);
}
})
$scope.s = $scope.$eval(angular.toJson(BelongsToThisDepartment));
// console.log(JSON.stringify($scope.s));
}
<div ng-app="MyApp">
<div ng-controller="MyController">
<table class="tableData" border="0" cellspacing="0" cellpadding="0" ng-init="DeptSpecific('1')">
<thead>
<tr>
<th></th>
<th>ID</th>
<th>NAME</th>
<th>LOCATION</th>
</tr>
</thead>
<tbody ng-repeat="O in s">
<tr ng-class-even="'even'" ng-class-odd="'odd'">
<td class="CX" ng-click="student(O.ID)"><span>+</span></td>
<td>{{O.ID}}</td>
<td>{{O.Name}}</td>
<td>{{O.Location}}</td>
</tr>
Looking at your code, using ng-init is fine, but your $scope.departments may not be accessible outside of the .success method.
angular.module('MyApp')
.controller('MyController', ['$scope', function($scope) {
$scope.DeptSpecific = function (ID) {
var BelongsToThisDepartment = [];
$http.get('/Department/getDept')
.success(function (response) {
$scope.departments = $scope.$eval(response);
angular.forEach($scope.departments, function (item1) {
if (item1.ID == ID) {
BelongsToThisDepartment.push(item1);
}
})
$scope.s = $scope.$eval(angular.toJson(BelongsToThisDepartment));
console.log($scope.s);
});
}
}]);
now if that works for you but you also want to be able to access $scope.s outside of that .success;
You can write a function, add it into .success pass the value returned onSucess, and do what you want to do.
.success(function(response) {
callAFunction(response);
}

function not executing on different view

I am new to angular JS. I have created a simple page using ngRoute.
In the first view I have a table, and on clicking it redirects to second view.
But I have called two functions using ng-click the changeView functions is running fine. But the second function fails to execute on the second view.
But Its running fine if using on the first view itself.
Heres the code for first view
Angular.php
<div ng-app="myApp" ng-controller="dataCtr">
<table class='table table-striped'>
<thead>
<tr>
<td>Title</td>
<td>Stream</td>
<td>Price</td>
</tr>
</thead>
<tbody>
<tr ng-repeat = "x in names | filter:filtr | filter:search" ng-click=" disp(x.id);changeView()">
<td >{{ x.Title }}</td>
<td>{{ x.Stream }}</td>
<td>{{ x.Price }}</td>
</tr>
</tbody>
</table>
</div>
heres the second View
details.php:
<div ng-app="myApp" ng-controller="dataCtr">
<div class="container">
SELECTED:<input type="textfield" ng-model="stxt">
</div>
</div>
heres the js file:
var app = angular.module("myApp", ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/angular', {
templateUrl: 'angular.php',
controller: 'dataCtr'
})
.when('/details', {
templateUrl: 'details.php',
controller: 'dataCtr'
})
.otherwise({
redirectTo: '/angular'
});
});
app.controller('dataCtr', function($scope ,$http ,$location ,$route ,$routeParams) {
$http({
method: "GET",
url: "json.php"})
.success(function (response) {$scope.names = response;});
$scope.changeView = function()
{
$location.url('/details');
};
$scope.disp = function(id)
{
$scope.stxt = $scope.names[id-1].Title;
};
});
The disp function is working fine on the angular view. But not being routed on the second view. I think the syntax for calling the two views in ng click is correct. OR if there any other method to call the associated table cell value to the second view. Please Help.
After a lots of research i figured it out.I used a factory service
app.factory('Scopes', function ($rootScope) {
var mem = {};
return {
store: function (key, value) {
$rootScope.$emit('scope.stored', key);
mem[key] = value;
},
get: function (key) {
return mem[key];
}
};
});
Added this to JS.
Because The scope gets lost on second Controller ,Services help us retain the scope value and use them in different controllers.Stored the scope from first controller
app.controller('dataCtr', function($scope ,$http ,$location,$rootScope,Scopes) {
Scopes.store('dataCtr', $scope);
//code
});
and loaded in the seconded controller.
app.controller('dataCtr2', function($scope ,$timeout,$rootScope,Scopes){
$scope.stxt = Scopes.get('dataCtr').disp;
});
Second view is not working because you cannot use $scope.$apply() method.
$apply() is used to execute an expression in angular from outside of the angular framework.$scope.$apply() right after you have changed the location Angular know that things have changed.
change following code part ,try again
$location.path('/detail');
$scope.$apply();

angular edit details using REST($resource) Service

I have a table with result set and there is edit option existing in each row. After clicking on the 'edit' link, i am able to populating the content on the fields.
But how do i edit the existing content using REST Service.
<table class="table-bordered table">
<thead>
<tr>
<th>id</th>
<th>Director</th>
<th>genre</th>
<th>releaseYear</th>
<th>title</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="result in results | orderBy:'_id'">
<td>{{result._id}}</td>
<td>{{result.director}}</td>
<td>{{result.genre}}</td>
<td>{{result.releaseYear}}</td>
<td>{{result.title}}</td>
<td>Edit | Delete</td>
</tr>
</tbody>
</table>
controller
$scope.saveContact = function(){
//save or edit contact
};
I have created in plunker.
content EDIT using REST API
I put it into work. You were close to the solution.
Here is the working plunker
What i did :
1 - I changed your way of getting the element for the form.
HTML
//I give the complete object instead of the id
ng-click="edit(result)"
Controller
//I prefer to pass the entire object
$scope.edit = function(result){
$scope.cineresultsFrm = angular.copy(result);
};
Service
I just removed the service. It wasn't useful anymore.
2 - I used the method of the ressource on your object
Controller
$scope.saveContact = function(){
//The function given to $update() is the .then() function
$scope.cineresultsFrm.$update(function(){
//If the update succeed i update the whole list. Could be done a better way but if you don't have any performance issues that will do the job.
$scope.getMovies();
});
};
I also changed the way you handle the "then" in the promise. But this is just a matter of taste.
$scope.getMovies = function(){
$scope.movieResults = movie.query(function() {
$scope.results = $scope.movieResults;
});
};
$scope.getMovies();
Hope it helped you

Angularjs state retension

I am adding row dynamically using angularjs. But the problem is that I want to retain this state all over the application. For example in view-1 I add one dynamic row to the table and move to view-2 after coming from view-2 the added row should be available. So is there any method to retain the state of view in angularjs. Following is the code I used to add row dynamically:
angular.module('MyApp', [])
.controller('MainController', [ '$scope', function($scope) {
$scope.rows = ['Row 1'];
$scope.counter = 2;
$scope.addRow = function() {
$scope.rows.push('Row ' + $scope.counter);
$scope.counter++;
}
}]);
<body ng-controller="MainController">
Add Row {{counter}}
<table>
<thead>
<tr>
<th width="200">Some Header</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="rowContent in rows">
<td>{{rowContent}}</td>
</tr>
</tbody>
</table>
</body>
Thanks.
Yes. You should save the model used to build the table (with the new rows aswell) to a Service. Then you inject that service in your controllers.
To be able to see a little bit of your code would be nice, though. But here goes an example of how to do this:
DISCLAIMER
Untested example
angular.module('yourapp').factory('MySharedService',function(){
var myTableModel = [];
function addRow(row){
myTableModel.push(row);
return myTableModel;
}
return {
addRow: addRow,
tableModel: myTableModel
}
})
.controller('MyFirstController',['$scope','MySharedService',function($scope,
MySharedService){
$scope.tableModel = MySharedService.tableModel;
$scope.addRow = function(row){
$scope.tableModel = MySharedService.addRow(row);
}
}]).controller('MySecondController',['$scope','MySharedService',function($scope,
MySharedService){...}]);
EDIT:
After researching a bit further on this, I've found a similar question with a couple ways of achieving this and with sample code here
Check it out and see if it helps you.

ng-repeat ng-click when the click function has already been called earlier in the code

First off, I read the plethora of other questions and answers regarding ng-click, ng-repeat, and child and parent scopes (especially this excellent one.)
I think my problem is new.
I'm trying to call a function using ng-click within a table. The app allows for the sorting of Soundcloud likes. The problem is that when I try to call the ng click function using new data, it still tries to call the function using the old data. Let me explain better with the example:
Controller:
function TopListCtrl($scope, $http) {
$scope.sc_user = 'coolrivers';
$scope.getData = function(sc_user) {
var url = 'http://api.soundcloud.com/users/'+ $scope.sc_user +'/favorites.json?client_id=0553ef1b721e4783feda4f4fe6611d04&limit=200&linked_partitioning=1&callback=JSON_CALLBACK';
$http.jsonp(url).success(function(data) {
$scope.likes = data;
$scope.sortField = 'like.title';
$scope.reverse = true;
});
}
$scope.getData();
$scope.alertme = function(permalink) {
alert(permalink);
};
}
HTML
<div id="topelems">
<p id="nowsorting">Now sorting the Soundcloud likes of <input type=text ng-model="sc_user"><button class="btn-default" ng-click="getData(sc_user);">Sort</button></p>
<p id="search"><input ng-model="query" placeholder="Filter" type="text"/></p>
</div>
<table class="table table-hover table-striped">
<thead>
<tr>
<th>Song</th>
<th>Artist</th>
<th>Likes</th>
<th>Played</th>
<th>Tags</th>
</tr>
</thead>
<tr ng-repeat="like in likes.collection | filter:query | orderBy:sortField:reverse">
<td width="30%"><a href="{{ like.permalink_url }}">{{like.title}}</td>
(Trying to call it here) <td>{{like.user.username}}</td>
<td>{{like.favoritings_count}}</td>
<td>{{like.playback_count}}</td>
<td>{{like.tag_list}}</td>
</tr>
</table>
</div>
</body>
</html>
So I have that function getData. I use it to load the data in using the soundcloud api. I have a form at the top that uses getData to load a new user's Soundcloud data in. I also call the getData function in the controller so that there is an example on the page upon loading.
The problem is when I try to load a new user's data from a <td> I want to be able to click on the user to see and sort their likes.
How do I 'clear' the function or the global namespace (am I even refering to the right thing)? How can I reuse the getData function with a new variable?
Working Jsfiddle for this
In your getData function you have this line:
var url = 'http://api.soundcloud.com/users/'+ $scope.sc_user +'/favorites.json...
but you are passing in the variable sc_user to your getData function and should be using it like this (no $scope):
var url = 'http://api.soundcloud.com/users/'+ sc_user +'/favorites.json...
That being said... your initial data load fails because you are calling:
$scope.getData();
and not:
$scope.getData($scope.sc_user);

Resources