AngularJS $http.get Parameter - javascript

I have a simple code here and got stuck in passing the parameter. Here is the code:
route.js
function config($routeProvider) {
$routeProvider
.when('/edit/:id', {
controller: 'UpdateTodoCtrl',
templateUrl: 'app/views/edit-todo.html'
});
}
index.html
<div ng-controller="SomeOtherCtrl">
<table>
<tr ng-repeat="t in todos">
{{ t.name }}
</tr>
</table>
</div
Controller
function UpdateTodoCtrl($http, $scope) {
function init() {
$scope.todos = null;
$scope.loading = true;
$http.get('app/endpoints/edit-todo.php', {
params: { todoId: //how to get the id paramter }
});
}
}
As you can ee in the controller, I commented out the part of my problem. How can I possibly pass the id in my url using $http.get? Thank you.

Your :id is a route parameter so you can do like this :
function UpdateTodoCtrl($http, $scope, $routeParams) {
function init() {
$scope.todos = null;
$scope.loading = true;
$http.get('app/endpoints/edit-todo.php', {
params: { todoId: $routeParams.id }
});
}
}

Related

AngularJS - Dynamic parameter in $http URL

The URL I use to retreive a JSON for my app has a dynamic parameter (:id ). I'm not too sure how I can work with this, so that it passes the ID the user has chosen. Just need a bit of guidance.
app.factory('bookcategories', ['$http', function($http) {
return $http.get('http://52.41.65.211:8028/api/v1/categories/:id/books.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
Controller
app.controller('BookCategoryController', ['$scope', 'categories', '$routeParams', function($scope, categories, $routeParams) {
categories.success(function(data) {
$scope.detail = data.categories[$routeParams.bookId];
$scope.currentCategoryIndex = parseInt($routeParams.categoryId);
$scope.myCategoriesDetails = $scope.category;
});
}]);
app.js
...
.when('/categories/:categoryId', {
controller: 'BookCategoryController',
templateUrl: 'views/booksincategory.html'
})
...
HTML
<h3 class="title">{{book.title}}</h3>
You could achieve this with a little service like the following code example. A factory is a wrong choice here.
app.service('bookCategories', ['$http', function($http) {
this.get = function (id) {
return $http.get('http://52.41.65.211:8028/api/v1/categories/'+ id + '/books.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
};
}]);
And than use it like:
app.controller('MyCtrl', function(bookCategories) {
bookCategories.get(1).then(function (result) {
console.log(result);
});
});

Getting Array of duplicate object instead of single object

I am writing a rather simple crud app, however, i seem to be stuck on the edit (Edit Controller) portion code. i have a list of student, i select one for update . but i get the error "Expected response to contain an object but got an array".
When i query the webservice directly, i get
But when i inspect elements and go to the network tab, i see this
here is my code.
var StudentManagement = angular.module('StudentManagement', ['ngRoute','ngResource','ui.bootstrap']);
StudentManagement.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "list.html",
controller: "HomeController"
})
.when("/add", {
templateUrl: "add.html",
controller: "AddController"
})
.when("/edit/:editId", {
templateUrl: "edit.html",
controller: "EditController"
})
.otherwise({
redirectTo: "/"
});
});
StudentManagement.factory('Student', function ($resource) {
return $resource('/api/Student/:id', { id: '#id' }, { update: { method: 'PUT' } });
});
StudentManagement.controller("HomeController",
function ($scope, $location, Student) {
$scope.search = function () {
$scope.students = Student.query();
};// end search
$scope.reset = function ()
{
$scope.search();
}// end reset function
$scope.search();
});
StudentManagement.controller("EditController",
function ($scope, $location, $routeParams, Student) {
// get the student given the specific id
var id = $routeParams.editId;
$scope.student=Student.get({id: id});
$scope.updateForm = function () {
Student.update({id:id}, $scope.student, function () {
$location.path('/');
});
}// end edit function
$scope.cancelForm = function () {
$location.path('/');
}// end cancel function
});
You are returning array of object from server.
So,you should add isArray : true in resource defination.
$resource('/api/Student/:id', { id: '#id' },
{ update: { method: 'PUT',isArray : true}
});
Or
you can return object of object from server
if you want to make current code workable

angular click on id should route to different page

Hi im new to angular and i have json data . SO when i click on Id obtained from json, it should route to different page. How should i do it
Head.html
</head>
<body ng-app="MyApp" ng-controller="MyController">
<table border="1" style="width:100%">
<tr >
<td href=#home>id</td>
<td>first_name</td>
<td>dateBirth</td>
<td>currentCountry</td>
</tr>
<tr ng-repeat="x in list">
<td>{{x.id}}</td>
<td>{{x.first_name}}</td>
<td>{{x.dateBirth}}</td>
<td>{{x.currentCountry}}</td>
</tr>
</table>
</body>
script.js
var app= angular.module("MyApp", []);
app.controller('MyController', function($scope,$http) {
$http({
method: "GET",
url: "http://192.168.1.1:8080/administrator/"
}).then(function mySucces(response) {
$scope.list = response.data;
console.log($scope.list)
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
my plunker http://plnkr.co/edit/Gpmsc7pb1gfWx3EgKk6s?p=preview
Any help is appreciated
There are various options to achieve what you are asking, using$routeProvider,$stateProvider and ng-click or ui-sref within that to achieve the navigation through id. I will go through a simple example using $stateProvider.
I will have 3 views to mock what you have provided:
header.html: which contains your ng-repeat to show the tabular data and whereby we have the click in the id to navigate.
first.html: if user clicks 1 in the id column, it is navigated to first.html
second.html: if user clicks 2 in the id column, it is navigated to second.html
Your JS:
var app = angular.module('nested', ['ui.router']);
app.config(function($stateProvider,$locationProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider.state('top', {
url: "",
templateUrl: "header.html",
controller: 'MyController'
})
.state('first', {
url: '/app/:id',
templateUrl: "first.html",
controller: 'FirstController'
})
.state('second', {
url: '/app/:id',
templateUrl: "second.html",
controller: 'SecondController'
})
});
app.controller('MyController', function($scope,$state) {
/*//commented this part so that you can work on it later.
$http({
method: "GET",
url: "http://192.168.1.134:8080/administrator/%20ApplicationList.json"
}).then(function mySucces(response) {
$scope.list = response.data;
console.log($scope.list)
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
*/
$scope.list = [{'id':1,'first_name':'alex','dateBirth':'18th march','currentCountry':'Nepal'},
{'id':2,'first_name':'rumba','dateBirth':'18th march','currentCountry':'USA'}
]
$scope.navigate = function(id){
if(id==1){
$state.go('first',{id:1});
}
else if(id==2){
$state.go('second',{id:2});
}
}
});
app.controller('FirstController', function($scope,$state) {
console.log(JSON.stringify($state.params));
$scope.params = $state.params;
});
app.controller('SecondController', function($scope,$state) {
console.log(JSON.stringify($state.params));
$scope.params = $state.params;
});
In this PLUNKER example, i have even provided how you pass params through controller:
http://plnkr.co/edit/n8p7ycV7k5rsn1f3bQcT?p=preview
You can add a ng-click attribute to your hyperlink tag like this
<td><a href="name.html" ng-click='displayFunc(x.id)'>{{x.id}}</a></td>
Now you can define this function in controller
$scope.displayFunc = function(id)
{
//Do something with id..
$location.path('/some route');
}
Don't forget to inject $location dependency in controller.

AngularJS ng-controller directive does not accept variable (scope function) from javascript, does not give any error either

I am relatively new to angularJS, I am trying to set up a page where inturn multiple pages are called depending upon the selection made previously.
All the pages have their own controller, so I am trying to set the controller and view src through the javascript and using them in HTML tags.
Following is what I am doing:
HTML page:
<div ng-if="sidebarName=='sidebar-device-wire'">
<div ng-controller="getSidebarCtlr">
<div ng-include src="sidebarSrc"></div>
</div>
</div>
javascript:
$scope.sidebarSrc="views/sidebars/sidebar-device.html";
$scope.sidebarCtlr="SidebarDeviceCtrl";
$scope.getSidebarCtlr = function(){return $scope.sidebarCtlr;}
For some reason though, this does not work. i can get the HTML page but the controller is not being called. Can anyone please tell me what I am doing wrong?
I would also recommend to use ngRoute or ui.router because there are many features that aren't easy to implement from scratch (like named views, nested views / nested states or resolves) and these modules are well tested.
Not sure why your controller isn't running but I guess that the expression of the controller is evaluated before your controller that is setting the name is running. So it will be always undefined at compile time.
But if you really like to implement a very basic router you could do it like in the following demo (or in this fiddle).
Update 21.12.2015
Here are some router examples that I wrote for other SO questions:
simple ui.router example - jsfiddle
more complex nested state example ui.router - jsfiddle
dynamic link list with ngRoute - jsfiddle
Please also have a look at ui.router github pages to learn more about it.
angular.module('simpleRouter', [])
.directive('simpleView', simpleViewDirective)
.provider('simpleRoutes', SimpleRoutesProvider)
.controller('MainController', MainController)
.controller('HomeController', HomeController)
.config(function(simpleRoutesProvider) {
simpleRoutesProvider.state([{
url: '/',
templateUrl: 'home.html',
controller: 'HomeController'
}, {
url: '/view1',
templateUrl: 'view1.html'
}, {
url: '/view2',
templateUrl: 'view2.html',
controller: function($scope) {
$scope.test = 'hello from controller'
}
}]);
simpleRoutesProvider.otherwise('/');
})
function HomeController($scope) {
$scope.hello = 'hello from home controller!!';
console.log('home controller started')
}
function MainController($scope) {
$scope.hello = 'Main controller test';
}
function simpleViewDirective() {
return {
restrict: 'EA',
scope: {},
template: '<div ng-include="templateUrl"></div>',
controller: function($scope, $location, $controller, simpleRoutes) {
var childControllerInst;
$scope.templateUrl = simpleRoutes.currentRoute.templateUrl || simpleRoutes.otherwise.templateUrl;
$scope.$watch(function() {
return $location.path();
}, function(newUrl) {
//console.log(newUrl)
$scope.templateUrl = simpleRoutes.changeRoute(newUrl);
childControllerInst = $controller(simpleRoutes.currentRoute.controller || function() {}, {$scope: $scope});
});
$scope.$on('$destroy', function() {
childControllerInst = undefined;
})
},
link: function(scope, element, attrs) {
}
}
}
function SimpleRoutesProvider() {
var router = {
currentRoute: {
templateUrl: ''
},
states: [],
otherwise: {},
changeRoute: function(url) {
var found = false;
angular.forEach(router.states, function(state) {
//console.log('state', state);
if (state.url == url) {
router.currentRoute = state;
found = true;
}
});
if (!found) router.currentRoute = router.otherwise;
//console.log(router.currentRoute);
return router.currentRoute.templateUrl;
}
};
this.state = function(stateObj) {
router.states = stateObj;
};
this.otherwise = function(route) {
angular.forEach(router.states, function(state) {
if (route === state.url ) {
router.otherwise = state;
}
});
//console.log(router.otherwise);
};
this.$get = function simpleRoutesFactory() {
return router;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="simpleRouter" ng-controller="MainController">
<script type="text/ng-template" id="home.html">home route {{hello}}</script>
<script type="text/ng-template" id="view1.html">view1</script>
<script type="text/ng-template" id="view2.html">view2 {{test}}</script>
<div simple-view="">
</div>
home
view1
view2
<br/>
{{hello}}
</div>
What's that code means? $scope.getSidebarCtlr = function(){return $scope.sidebarCtlr;}
the ng-directive requires a Controller name, its argument type is string and you cannot pass a simple function, you need to register a valid controller associating it to a module via the controller recipe.
https://docs.angularjs.org/guide/controller
angular.module('test', []).controller('TestCtrl', function($scope) {
$scope.greetings = "Hello World";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<article ng-controller="TestCtrl">{{ greetings }}</article>
</section>

data-ng-repeat in partial view does not display data

This is my module.js
var app = angular.module("ApplicationModule", ["ngRoute"]);
app.factory("ShareData", function () {
return { value: 0 }
});
//Showing Routing
app.config(['$routeProvider', '$locationProvider', function
($routeProvider, $locationProvider) {
debugger;
$routeProvider.when('/ShowAll',
{
templateUrl: 'Home/ShowAll',
controller: 'ShowAllController'
});
$routeProvider.otherwise(
{
redirectTo: '/'
});
}]);
This is my Services.js
app.service("SampleService", function ($http) {
this.getSamples = function () {
return $http.get("/api/Sample");
};
this.getSample = function (id) {
return $http.get("/api/Sample" + id);
};
});
This is my ShowAllController.js
app.Controller('ShowAllController', function ($scope,
SampleService) {
loadAll();
function loadAll() {
var promiseGet = SampleService.getSamples();
promiseGet.success(function (data) { $scope.Samples = data
},
function (errordata) {
$scope.error = errordata;
}
);
}
});
This is my index.cshtml
#{
ViewBag.Title = "API's";
}
#section scripts{
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-route.min.js"></script>
<script src="~/Scripts/Module.js"></script>
<script src="~/Scripts/Services.js"></script>
<script src="~/Scripts/ShowAllController.js"></script>
}
<div class="container" data-ng-app="ApplicationModule">
<div class="panel panel-default">
<div class="panel-header">
<div class="row">
<div><h4 class="col-xs-6">GET api/Patient</h4>Patients List</div>
</div></div>
<div class="panel-body" data-ng-view>
</div>
</div>
This is my partial view (ShowAll.cshtml)
<div data-ng-controller="ShowAllController">
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Address</th>
</tr>
<tr data-ng-repeat="person in Samples">
<td>{{person.Id}}</td>
<td>{{person.Name}}</td>
<td>{{person.Age}}</td>
<td>{{person.Address}}</td>
</tr>
</table>
</div>
My return PartialView code is in my HomeController inside the ShowAll ActionResult. The problem is that when I click the button it just displays the header of the table without the data.
Note: This is a web api.
Thank you.
Add the following statement to your ShowAllController before the ajax call so Angular is aware of this scope var in Config time
app.Controller('ShowAllController', function ($scope, SampleService) {
$scope.Samples = []; // <- NEW LINE HERE!
loadAll();
function loadAll() {
var promiseGet = SampleService.getSamples();
promiseGet.success(function (data) { $scope.Samples = data
},
function (errordata) {
$scope.error = errordata;
}
);
}
});
Angular Dependency Injection might not be setting up the scope var Samples in Config time. Then in Run time, it won't recognize this var as something that should be updated.
If that doesn't work, also try to wrap the success result of of your promise into $scope.$apply() as angular might not be aware of it when running its digest function.
$scope.$apply(function () {
$scope.Samples = data;
})

Categories

Resources