i have 2 controller loaded in one page : one loaded by $routeProvider,
application.js
.when('/service/:serviceId/:serviceName/',
{
templateUrl : 'view/service/service.html',
controller : 'ServiceController'
})
the other loaded in the view
service.html
<div align="left">
<table class="table-flag">
<tr ng-controller="LanguageController">
<td ng-repeat="language in listLanguage"
width="50">
<input type="image" ng-src="img/flags/{{language.code}}.jpg"width="30" height="20"></input> </a>
</td>
</tr>
</table>
<div>
<br />
<ul>
<table class="table table-hover">
<tbody>
<tr
ng-repeat="detail in service.infoList">
<td><span ng-bind-html-unsafe="detail.label"></span></td>
</tr>
</tbody>
</table>
</ul>
</div>
</div>
I retrieve some datas from a server using rest
ServiceController
Info.controller('ServiceController', function ServiceController(
$scope, $http, $routeParams, manageDatas) {
$scope.serviceId = $routeParams.serviceId;
$scope.serviceName = $routeParams.serviceName ;
var paramsService = {
serviceId : $scope.serviceId,
serviceName : $scope.serviceName
};
$scope.loading = true;
var response = $http({
url : 'rest/service',
params : paramsService,
method : 'GET'
});
response.success(function(service) {
$scope.service = service;
$scope.loading = false;
manageDatas.setArrayData($scope.service.languageList); // service which allow to pass an array in LanguageController
});
});
LanguageController
LanguageController.controller('LanguageController', function ServiceByLanguageController(
$scope, $http, $routeParams, $timeout , manageDatas , $route) {
$scope.listLanguage = manageDatas.getDatas(); // retrieve the array passed in ServiceController by a service
// always null
});
The problem is the $http.success method in ServiceController is always executed AFTER LanguageController(verified by breakpoints) so the array $scope.listLanguage is always empty because i don t pass datas....
How can i make the languageController be executed after all the treatments in serviceController finish ?
Thank you very much
Alternatively, you can broadcast event in response.success(function(service) {...}, say, using $rootScope, and let LanguageController listen to this event and then do assignment $scope.listLanguage = ...
Just after a brief look, I would say that part or all of your ServicesController logic should be in a service and not a controller. You seem to have such a service in manageDatas. Just put all the code that actually loads and writes data to the service inside the service.
Related
Trying to write a simple SPA. Using MEAN.
API through node are all working.
Have set up routes in my main controller
// create the module and name it
var boardingApp = angular.module('boardingApp', ['ngRoute']);
boardingApp.config(function($routeProvider) {
$routeProvider
// route for the home page that lists all tenants
.when('/', {
templateUrl : 'js/templates/tenants.html',
controller : 'tenantsController'
})
// route for a specifc tenant
.when('/tenant/:id', {
templateUrl : 'js/templates/tenant.html',
controller : 'tenantController'
})
});
boardingApp.controller('tenantsController', ['$scope','$http','$log', function($scope, $http,$log) {
$http.get(URL + "/api/tenants")
.then(function(response){ $scope.details = response.data; });
}]);
boardingApp.controller('tenantController', ['$scope','$http','$location','$log', function($scope, $http, $location, $log) {
if ( $location.search().hasOwnProperty( 'id' ) ) {
var myid = $location.search()['id'];
console.log(myid)
myURL = URL + "/api/tenants/"+myid
console.log(myURL)
$http.get(myURL)
.then(function(response){ $scope.tenant = response.data; });
console.log($scope.tenant)
}
}]);
boardingApp.controller('readmeController', function($scope, $http) {
$scope.message = "This is the message"
});
the root route work finds calls the API generates a table. All good
then main part of that template is this
<tbody id="tenantsTable">
<tr ng:repeat = "tenant in details | filter : true: tenant.activeTenant ">
<td><a ng-href = "#/tenant.html?id={{tenant._id}}" >View</td>
<td>{{tenant.roomNumber}} </td>
<td>{{tenant.firstName}} </td>
<td>{{tenant.lastName}} </td>
<td>{{tenant.paymentFrequency}} </td>
<td>${{tenant.rentAmount}} </td>
<td> {{tenant.leaseEnd | date: 'dd MMM yyyy'}} </td>
</tr>
</tbody>
I want to click on the "View" link and pull data from DB for each tenant through and API call that just needs the Tenant id - standard stuff.
My controller is not picking up the request and when i click on the link on the Tennants page it just ends up blank.
what am i missing here? the api call s are all good and working fine
You anchor tab is incorrect, it should be in correct pattern like "#/tenant/{{tenant._id}}"
ng-href="#/tenant/{{tenant._id}}"
Additionally you should retrieve a route parameter inside tenantController by using $routeParams.id API instead of $location.search() which would be look for query parameter.
I'm trying to delete a row in a table generated using angular ng-repeat directive and I get a "DELETE http://localhost:3000/api/delbike 404 (Not Found)" error. I suspect this to be an issue at the server end, but I'm also not getting the parameter to be passed to the $http service on angular end. Any help will be greatly appreciated. I expect $scope.bikes[idx] to pass the bike object selected for deletion. however while debugging it shows as undefined.Below is the angular code
//controller
ub.controller('bikectrl',["$scope","fbauthFact","$log","bike",function($scope,fbauthFact,$log,bike){
$log.log("In bike controller");
$scope.msg = "";
$scope.bikes =[];//bikes array to store bikes retrieved for a user
$scope.bike ={};//bike object to submit details of bike
//var bike ={};
var idx;
$scope.usr = fbauthFact.getResponseobj();
bike.getbikes($scope.usr).then(function(response){
$scope.bikes = response;
},function(reason){
$scope.msg = reason;
});//getbikes
$scope.delbike = function(idx){
$scope.bikes.splice(idx,1);
bike.delbike($scope.bikes[idx]).then(function(response){
$scope.msg = response;
},function(reason){
$scope.msg = reason;
});
};
}]);
//factory
ub.service('bike',['$http','fbauthFact','$log','$q',function($http,fbauthFact,$log,$q){
var user={};
var bike={};
//retrieve bikes
this.getbikes = function(user){
var deferred = $q.defer();
$http({
method:"GET",
url:"http://localhost:3000/api/getbike",
params: user
}).then(function successCallback(srresponse){
deferred.resolve(srresponse.data);
},
function failureCallback(srresponse){
$log.error("get bikes http call failed ",srresponse.data);
deferred.reject(srresponse.data);
});//$http
return deferred.promise;
};//getbikes
//delete bike
this.delbike = function(bike){
var deferred = $q.defer();
$http({
method:"DELETE",
url:"http://localhost:3000/api/delbike",
params: bike
}).then(function successCallback(srresponse){
deferred.resolve(srresponse.data);
},function failureCallback(srresponse){
deferred.reject(srresponse.data);
});
return deferred.promise;
};//delbike
}]);
//html
<div>
<div class='container' style='margin-top:90px;'>
<div class='row'>
<div class='col-md-8'>
<h3>Bikes of {{usr.first_name}}. Click here to add</h3>
</div>
</div>
</div>
<div class='container'>
<div class='table-responsive'>
<table class='table table-hover'>
<thead>
<tr>
<th>#</th>
<th>Make</th>
<th>Regno</th>
<th>Model</th>
<th>Year</th>
<th>Delete?</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in bikes">
<td>{{$index+1}}</td>
<td>{{x.brand}}</td>
<td>{{x.regno}}</td>
<td>{{x.model}}</td>
<td>{{x.year}}</td>
<td>
<button type="button" ng-click="delbike($index)" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>
</td>
</tr>
</tbody>
</table>
</table>
</div>
</div>
//server side snippet
app.delete('/api/delbike/*',function(req,res){
ubBike.remove({regno:req.query.regno},function(err,results){
if(err) throw err;
if(results.result.n==0)
{
res.send('Bike not registered');
}
else
{
res.send('Success');
}
});
});
Not sure about the first case of getting 404 not found
http://localhost:3000/api/delbike
It might be the server side issue or something buggy
but for the second case:
It will be undefined as you're removing it using this
$scope.bikes.splice(idx,1);
Before sending it to service for further processing
Try writting above block inside the resolver of the delete call
So you delbike method inside controller will look like following
$scope.delbike = function(idx){
bike.delbike($scope.bikes[idx]).then(function(response){
$scope.msg = response;
$scope.bikes.splice(idx,1); // add it here
},function(reason){
$scope.msg = reason;
});
};
Please checkout is your server side method type is HTTPDELETE or POST?
If it is POST Method then you need to change your Method type on your HTTP call
change method:"POST", it instead of method:"DELETE",
Also you don't need $scope.bikes.splice(idx,1); delete the object in the array, because the server also return deleted results.
I was able to resolve the issue by removing the slash '/' a the end of the router url in the api
app.delete('/api/delbike*',function(req,res){..
I'm setting up an Angular JS app that consumes a Django REST API.
I want to show a HTML list of classrooms.
This is my template
<body>
<div ng-app="schoolApp" ng-controller="schoolCtrl">
<table class="table table-striped">
<thead>
<tr>
<th>Classroom</th>
<th>School</th>
<th>Floor</th>
<th>Academic year</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="classroom in classrooms">
<td>{{classroom.classroom}}</td>
<td>{{classroom.school.school_name}}</td>
<td>{{classroom.floor}}</td>
<td>{{classroom.academic_year}}</td>
</tr>
</tbody>
</table>
</div>
</body>
This is the script
var schoolApp = angular.module('schoolApp', ['ngResource']);
schoolApp.factory('Classroom', ['$resource', function($resource) {
return $resource('/classrooms/?format=json', {}, {
query: {
method: 'GET',
isArray: true,
}
});
}]);
schoolApp.controller('schoolCtrl', function($scope, Classroom) {
Classroom.query().$promise.then(function(data) {
var data = Classroom.query({});
$scope.classrooms = data;
console.log(Classroom.query({}));
});
});
The problem is, I think, that I get - I can see it in the console -, $resolved: false.
How can I resolve that?
UPDATE:
Given that I can't resolve the issue, I was wondering that maybe I've set up badly something else, like... the view?
This is the one I got
class HomePageView(TemplateView):
template_name = 'school_app/base.html'
class StudentViewSet(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
class ClassroomViewSet(viewsets.ModelViewSet):
queryset = Classroom.objects.all()
serializer_class = ClassroomSerializer
Maybe I have to add something to HomePageView or setting it up in another way?
UPDATE:
This is what I get on the console with the debugger "on"
Success: [{"school":{"id":1,"school_name":"IPSIA F. Lampertico","address":"Viale Giangiorgio Trissino, 30","city":"Vicenza"},"academic_year":"2015/2016","classroom":"1^A","floor":0,"students":[{"classroom":1,"first_name":"Stefano","last_name":"Rossi","gender":"M","birthday":"1998-06-22"},{"classroom":1,"first_name":"Luca","last_name":"Possanzini","gender":"M","birthday":"1999-11-22"}]},{"school":{"id":2,"school_name":"ITIS A. Rossi","address":"Via Legione Gallieno, 52","city":"Vicenza"},"academic_year":"2015/2016","classroom":"2^B","floor":0,"students":[{"classroom":2,"first_name":"Sergio","last_name":"Lazzari","gender":"M","birthday":"2001-01-29"}]},{"school":{"id":3,"school_name":"Liceo Scientifico G.B. Quadri","address":"Viale Giosuè Carducci, 17","city":"Vicenza"},"academic_year":"2015/2016","classroom":"3^C","floor":0,"students":[{"classroom":3,"first_name":"Lucia","last_name":"Modella","gender":"F","birthday":"2000-05-22"}]},{"school":{"id":4,"school_name":"Istituto Professionale Statale B.Montagna","address":"Via Mora, 93","city":"Vicenza"},"academic_year":"2015/2016","classroom":"4^D","floor":1,"students":[{"classroom":4,"first_name":"Mirko","last_name":"Van Der Sella","gender":"M","birthday":"2002-12-25"}]}]
Practically, the whole Json response.
When you call query of $resource, it returns a reference to an object or array with $resolved = false, until the REST API calls finishes and populates your object. So, $resolved = false is probably correct and indicates that you have not receive the data yet.
Here is a working plunker based on your code.
The controller is:
app.controller('schoolCtrl', function($scope, Classroom) {
var vm = this;
vm.name = 'World';
Classroom.query().$promise.then(function(data) {
console.log('Success: '+JSON.stringify(data));
vm.classrooms = data;
}, function (reason) {
console.log('ERROR: '+JSON.stringify(reason));
});
});
This is what I do for debugging REST web API... once the call works, you can switch to a lighter version:
app.controller('schoolCtrl', function($scope, Classroom) {
var vm = this;
vm.name = 'World';
vm.classrooms = Classroom.query();
});
I created a classroom JSON (guessing your format):
[
{"classroom":"0", "school": {"school_name":"anc"} },
{"classroom":"1", "school": {"school_name":"Sorbonee"} }
]
And the HTML:
<body ng-controller="schoolCtrl as vm">
<p>Hello {{vm.name}}!</p>
<div>
<table class="table table-striped">
<thead>
<tr>
<th>Classroom</th>
<th>School</th>
<th>Floor</th>
<th>Academic year</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="classroom in vm.classrooms">
<td>{{classroom.classroom}}</td>
<td>{{classroom.school.school_name}}</td>
<td>{{classroom.floor}}</td>
<td>{{classroom.academic_year}}</td>
</tr>
</tbody>
</table>
</div>
</body>
I changed the URL in the factory to make it work on plnkr, but the rest is identical:
app.factory('Classroom', ['$resource', function($resource) {
return $resource('classrooms?format=json', {}, {
query: {
method: 'GET',
isArray: true,
}
});
}]);
Please note that I use var vm=this and ControllerAs syntax to avoid any scope issues based on this article.
On ngResource from the doc: "It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods."
Let us know if this helps.
I am pretty new to angular and I am working on a data entry web page. The web page has three tabs. Vendor, Products and Types. I started working on the Types tab first. I'd be happy if I could just display the results of a GET request to my Rest API. My Rest API works:
# curl http://192.168.1.115:8080/type
[
{"_id":"56415e7703aba26400fcdb67","type":"Skiing","__v":0},
{"_id":"56417a8503aba26400fcdb68","type":"Bannana","__v":0},
{"_id":"56417a8d03aba26400fcdb69","type":"Carrot","__v":0},
{"_id":"56417a9603aba26400fcdb6a","type":"Beer","__v":0}
]
Here's the pertinent part of my html UPDATED I now have st-safe-src=all_typesbut still no joy ...
<div ng-controller="typeCtrl" class="tab-pane" id="types-v">
<p>The number {{3 + 4}}.</p>
<p>message is {{message}}</p>
<table st-table="displayedCollection" st-safe-src="all_types" class="table table-striped">
<tbody>
<tr ng-repeat="x in displayedCollection">
<td>{{x.type}}</td>
</tr>
</tbody>
</table>
</div> <!-- end Types Tab -->
... and here is my typeCtrl.js ...
app.controller("typeCtrl", function($scope,$http) {
$scope.type_to_look_for = "";
$scope.message = "this is the message. (from typeCtrl)";
$scope.itemsByPage=15;
$scope.all_types = function () {
$http.get("http://192.168.1.115:8080/type").then(function(response) {
console.log(response);
console.log(response.data);
return response.data;
});
}
});
... but when I click on the Types tab my data does not display. I looked developer console and I do not even see the GET request kickoff. And my web page looks like this ...
... what am I doing wrong?
There is nothing that calls all_types. Run http.get and assign the response to all_types
app.controller("typeCtrl", function($scope,$http) {
$scope.type_to_look_for = "";
$scope.message = "this is the message. (from typeCtrl)";
$scope.itemsByPage=15;
$http.get("http://192.168.1.115:8080/type").then(function(response) {
$scope.all_types = response;
});
}
});
My understanding is that you want a get request to be fired whenever you click on the Types tab, right? If so, just use ng-click to call your all_types function as follows:
<div ng-controller="typeCtrl" ng-click="all_types()" class="tab-pane" id="types-v" >
Also, you do not need to return response.data in your controller. Just assign the data to a scope object and use it in the template.
And finally, I would suggest wrapping all your ajax calls in factories and then inject those factories in your controllers.
Here is your code
<div ng-controller="typeCtrl" class="tab-pane" id="types-v">
<p>The number {{3 + 4}}.</p>
<p>message is {{message}}</p>
<table st-table="types" class="table table-striped"><!-- Do not need st-safe-src -->
<tbody>
<tr ng-repeat="x in types"><!-- Use the Collection name as types-->
<td>{{x.type}}</td>
</tr>
</tbody>
</table>
</div>
Controller Code
app.controller('typeCtrl', function($scope, $http) {
$scope.type_to_look_for = "";
$scope.message = "this is the message. (from typeCtrl)";
$scope.itemsByPage=15;
$http.get("http://192.168.1.115:8080/type").then(function(response) {
console.log(response.data);
$scope.types = response.data;
});
});
Here is working the plunker
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();