I'm new on angular js and i'm trying to get parameters from the url i've read some documentation about routeparams but i'm getting it empty.
here is my code
var study = angular.module('study', ['ngRoute'], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
study.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('edit/:id', {
controller: 'EditController'
});
}]).controller('EditController',
function($scope, $http, $compile, $rootScope, $routeParams, $route ) {
$scope.item = null;
console.log($routeParams);
console.log($rootScope);
var id = $routeParams.$id;
$scope.onLoad = $http({
method: 'get',
url: 'item',
data: {id:id}
}).success(function(data, status, headers, config) {
$scope.item = data;
}).error(function(data, status, headers, config) {
alert(status);
});
});
Related
Although there are many questions regarding the subject , yet I am unable to figure it out , how to proceed further.
I am new in AngularJS. I want to pass data coming from API in Controller and pass it to another function. For this I know I have to create a Service. But after coming to this extend of code I am unable to figure it, how to store it in Service and pass it on other Controller or of function within same Controller. I am new in making Service.
Controller:
$scope.GetR = function (){
$scope.X = null;
$scope.Y = null;
$http({method: 'POST', url: 'http://44.43.3.3/api/infotwo',
headers: {"Content-Type": "application/json"},
data: $scope.ResponseJson
})
.success(function(data, status, headers, config) {
$scope.X = data.X;
$scope.Y = data.Y;
//console.log($scope.X+"and"+$scope.Y);
//Seding RS to API to get AAs
$scope.RJson = {
"ICl": $scope.ICl,
"RS": $scope.X
};
$http({method: 'POST', url: 'http://44.128.44.5/api/apithree',
headers: {"Content-Type": "application/json"},
data: $scope.RJson
})
.success(function(data, status, headers, config) {
$scope.At = data;
$scope.Eq = data.AA.Eq;
$scope.FIn = data.AA.FIn;
$scope.MM = data.AA.MM;
console.log("Eq:"+$scope.Eq+" FIn:"+$scope.FIn+" MM:"+$scope.MM);
}).error(function(data, status, headers, config) {
console.log("API failed...");
});
}).error(function(data, status, headers, config) {
console.log("Something went wrong...");
});
};
Now I want to pass this data to Service so that I can call this output on other API input
.success(function(data, status, headers, config) {
$scope.At = data;
$scope.Eq = data.AA.Eq;
$scope.FIn = data.AA.FIn;
$scope.MM = data.AA.MM;
console.log("Eq:"+$scope.Eq+" FIn:"+$scope.FIn+" MM:"+$scope.MM);
This shows how to create a service and share data between two controllers.
The service:
(function() {
'use strict';
angular
.module('myAppName') // Replace this to your module name
.service('MyService', MyService);
MyService.$inject = [];
function MyService() {
this.data = null;
}
})();
First controller:
(function() {
'use strict';
angular
.module('myAppName') // Replace this to your module name
.controller('MyFirstController', MyFirstController);
MyFirstController.$inject = ['MyService', '$http'];
function MyFirstController(MyService, $http) {
var vm = this;
vm.data = MyService.data;
$http.post('/someUrl', whatEverData).then(resp=> {
MyService.data = resp.data;
})
}
})();
Second controller:
(function() {
'use strict';
angular
.module('myAppName') // Replace this to your module name
.controller('MySecondController', MySecondController);
MySecondController.$inject = ['MyService', '$http'];
function MySecondController(MyService, $http) {
var vm = this;
vm.data = MyService.data; // Here you can use the same data
}
})();
Not sure if this is what you are looking for. Below code is not tested (May have syntax errors)
Service:
function() {
'use strict';
angular
.module('myAppName')
.factory('MyService', MyService);
MyService.$inject = [];
function MyService() {
var data = null;
return {
getData: function() {
return data;
},
setData: function(d) {
data = d;
}
}
}
})();
Controller:
(function() {
'use strict';
angular
.module('myAppName')
.factory('controller', controller);
controller.$inject = ['$scope', '$http', 'MyService'];
function controller($scope, $http, MyService) {
$scope.GetR = function() {
$scope.X = null;
$scope.Y = null;
var promise = $http({
method: 'POST',
url: 'http://44.43.3.3/api/infotwo',
headers: {
"Content-Type": "application/json"
},
data: $scope.ResponseJson
});
promise.success(function(data, status, headers, config) {
$scope.X = data.X;
$scope.Y = data.Y;
//console.log($scope.X+"and"+$scope.Y);
//Seding RS to API to get AAs
$scope.RJson = {
"ICl": $scope.ICl,
"RS": $scope.X
};
}).error(function(data, status, headers, config) {
console.log("Something went wrong...");
});
return promise;
};
$scope.sendRS = function() {
var promise = $http({
method: 'POST',
url: 'http://44.128.44.5/api/apithree',
headers: {
"Content-Type": "application/json"
},
data: $scope.RJson
});
promise.success(function(data, status, headers, config) {
$scope.At = data;
$scope.Eq = data.AA.Eq;
$scope.FIn = data.AA.FIn;
$scope.MM = data.AA.MM;
console.log("Eq:" + $scope.Eq + " FIn:" + $scope.FIn + " MM:" + $scope.MM);
}).error(function(data, status, headers, config) {
console.log("API failed...");
});
return promise;
}
var init = function() {
$scope.GetR().then(function() {
$scope.sendRS().then(function(data) {
MyService.setData({
At: data,
Eq: data.AA.Eq,
FIn: data.AA.FIn,
MM: data.AA.MM
});
})
})
}
init();
}
})();
Other controller
(function() {
'use strict';
angular
.module('myAppName')
.controller('controller1', controller1);
controller1.$inject = ['$scope', 'MyService'];
function controller1($scope, MyService) {
$scope.data = MyService.getData();
}
})();
There is a register form. On submit of register form I am trying to save the data through angular service. It is giving me an error Error: [$http:badreq]
This is my register.controller.js
(function(){
var app = angular.module('myapp');
app.controller('RegisterController',RegisterController);
RegisterController.$inject = ['UserService', '$location','$rootScope'];
function RegisterController(UserService, $location, $rootScope) {
var vm = this;
vm.register = register;
function register(){
UserService.Create(vm.user)
.then(function(response)
{
if(response.success){
}else{
}
});
}
};
})();
Here is the UserService
(function () {
'use strict';
angular
.module('myapp')
.factory('UserService', UserService);
UserService.$inject = ['$timeout', '$filter', '$q', '$http'];
function UserService($timeout, $filter, $q, $http) {
var service = {};
service.Create = Create;
return service;
var url='ajax.php';
function Create(user) {
$http({
method: 'post',
url: url,
data: user,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
success(function(data, status, headers, config) {
console.log(data);
}).
error(function(data, status, headers, config) {
console.log(data);
});
}
}
})();
What is the issue with code. Please help. Thanks in advance
You are using return service; prior to define the URL so the $http service get's undefined instead of URL. Solution is to move return statement in the last of the service function like:
(function () {
'use strict';
angular
.module('myapp')
.factory('UserService', UserService);
UserService.$inject = ['$timeout', '$filter', '$q', '$http'];
function UserService($timeout, $filter, $q, $http) {
var service = {};
service.Create = Create;
var url='ajax.php';
function Create(user) {
$http({
method: 'post',
url: url,
data: user,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
success(function(data, status, headers, config) {
console.log(data);
}).
error(function(data, status, headers, config) {
console.log(data);
});
}
return service;
}
})();
I'm trying to get ui-router to work and I'm getting pretty close. Well I got it working, but I can't combine it with my controller, then I'm getting errors.
I'm getting this error in the console
Error: [ng:areq] Argument 'searchCtrl' is not a function, got undefined
searchCtrl.js
var myApp = angular.module('myApp')
.controller('searchCtrl', [
'$scope', '$http', function($scope, $http) {
$scope.search = function() {
var base = 'http://api.themoviedb.org/3';
var service = '/search/movie';
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
var search = $scope.searchquery
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + service + '?api_key=' + apiKey + search + '&callback=' + callback;
$http.jsonp(url,{ cache: true}).
success(function (data, status, headers, config) {
if (status == 200) {
$scope.movieList = data.results;
console.log($scope.movieList)
} else {
console.error('Error happened while getting the movie list.')
}
}).
error(function (data, status, headers, config) {
console.error('Error happened while getting the movie list.')
});
}
}
]);
My searchModule.js
var app = angular.module('movieseat', ['ui.router']).config([
'$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/state1');
return $stateProvider.state('state1', {
url: '/state1',
templateUrl: 'assets/angular-app/templates/state1.html'
});
}
]);
And my app.js.coffee
#app = angular.module('movieseat', []);
#myApp = angular.module('myApp',[]);
# for compatibility with Rails CSRF protection
#app.config([
'$httpProvider', ($httpProvider)->
$httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content')
])
#app.run(->
console.log 'angular app running'
)
This might be the same question and I've tried adding another module to my app.js.coffee but it's not working.
Does anyone have a tip?
Change first two module declaration line of your app.js.coffee like below.
#myApp = angular.module('myApp',[]);
#app = angular.module('movieseat', ['myApp','ui.router']);
and then in searchModule.js
angular.module('movieseat').config([
'$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/state1');
return $stateProvider.state('state1', {
url: '/state1',
templateUrl: 'assets/angular-app/templates/state1.html'
});
}
]);
REASON : Here you are basically overriding the module you previously created insted you just need to use that already declared module.
If you are doing with single module then
#app = angular.module('movieseat', ['myApp','ui.router']);
# for compatibility with Rails CSRF protection
#app.config([
'$httpProvider', ($httpProvider)->
$httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content')
])
#app.run(->
console.log 'angular app running'
)
and
angular.module('movieseat').config([
'$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/state1');
return $stateProvider.state('state1', {
url: '/state1',
templateUrl: 'assets/angular-app/templates/state1.html'
});
}
]);
and your controller looks like
angular.module('movieseat')
.controller('searchCtrl', [
'$scope', '$http', function($scope, $http) {
$scope.search = function() {
var base = 'http://api.themoviedb.org/3';
var service = '/search/movie';
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
var search = $scope.searchquery
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + service + '?api_key=' + apiKey + search + '&callback=' + callback;
$http.jsonp(url,{ cache: true}).
success(function (data, status, headers, config) {
if (status == 200) {
$scope.movieList = data.results;
console.log($scope.movieList)
} else {
console.error('Error happened while getting the movie list.')
}
}).
error(function (data, status, headers, config) {
console.error('Error happened while getting the movie list.')
});
}
}
]);
I'm sure this problem has a simple answer, but, for once, I'm stumped. I want to have a URL like http://www.website.com/item/1234 display information about an item with id '1234'. I have an Angular controller set up to query for it and render its data. This works, provided the id is valid. However, I can't figure out how to pass the id, in the first place. I have tried lots of routing examples, but none of them work when I try to implement them, so I'm missing something.
Here is the server route in Express/Node:
router.get('/item/:id', function(req, res, next) {
res.render('item');
});
Here is the Angular route:
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when('/item/:id', {
controller: 'ShowItem'
});
$locationProvider.html5Mode(true);
}]);
The controller is trying to access 'id' here:
app.controller('ShowItem', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
console.log($routeParams.id);
var itemID = $routeParams.id;
$http({
method: 'GET',
url: '/queries/get_item',
params: {
itemID: itemID
}
}).success(function(data, status, headers, config) {
if (data) {
$scope.itemValue = data;
$scope.type = $scope.itemValue['SaleType'];
$scope.setAllBidHistory(false);
if (Date.getStamp() >= $scope.itemValue['ExpirationTimeStamp']) {
$scope.expired = true;
} else {
$scope.expired = false;
}
}
}).error(function(data, status, headers, config) {
alert('There was an error fetching item: '+status);
});
...
}]);
The page renders, but $routeParams.id is undefined.
I'm pretty new to with AngularJS. When I'm calling $http.get I get a $http is not defined error.
This is the content of my Module:
var demoApp = angular.module('demoApp', []);
demoApp.config(function ($routeProvider) {
$routeProvider.
when('/view1',
{
controller: 'SimpleController',
templateUrl: 'View1.html'
}).
when('/view2',
{
controller: 'SimpleController',
templateUrl: 'View2.html'
})
.otherwise({ redirectTo: '/view1' });
});
demoApp.factory('simpleFactory', function () {
var factory = {};
factory.getAnnounces = function ($http) {
$http.post("http://localhost:57034/Announce/GetAllAnnounces")
.success(function (data, status, headers, config) {
return data;
}).error(function (data, status, headers, config) {
return status;
});
};
return factory;
});
demoApp.controller('SimpleController', function ($scope,simpleFactory) {
$scope.announces = [];
init();
function init()
{
$scope.announces= simpleFactory.getAnnounces();
}
});
What am I missing here? Cheers.
You need to review your code as follows:
demoApp.factory('simpleFactory', ['$http', function ($http) {
return {
getAnnounces: function () {
$http.post("http://localhost:57034/Announce/GetAllAnnounces")
.success(function (data, status, headers, config) {
return data;
}).error(function (data, status, headers, config) {
return status;
});
}
};
}]);
There's no need to pass the $http variable in the getAnnounces method definition, because it is defined already in the scope of the factory function.
I am using parameter aliasing for AngularJS in order to avoid issues with minifiers, see 'A note on minification' on the AngularJS web site.
Note anyway that $http.post.success and $http.post.error are asynchronous and you won't be able to get the data unless you're using promises ($q), see here. Therefore you could change the code this way:
demoApp.factory('simpleFactory', ['$http', '$q', function ($http, $q) {
return {
getAnnounces: function () {
var deferred = $q.defer();
$http.post("http://localhost:57034/Announce/GetAllAnnounces")
.success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
}
};
}]);
And in the SimpleController:
demoApp.controller('SimpleController', ['simpleFactory', '$scope', function (simpleFactory, $scope) {
$scope.announces = [];
simpleFactory.getAnnounces()
.then(function(data) {
// call was successful
$scope.announces = data;
}, function(data) {
// call returned an error
$scope.announces = data;
});
}]);