AngularJS pass param from view to controller - angularjs

I'm a beginner in angularjs. What I’m trying to do is from view to pass params to the controller, which to return at its side, different results from factory. The problem is that when it goes to call metod with params from some view the result is an infinity loop.
I've the following config:
app.config(function($locationProvider, $stateProvider, $urlRouterProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
}).hashPrefix('!');
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'templates/home.html',
controller: 'StoreController as store'
})
})
My Factory is:
app.factory('BookFactory', function($http, $q){
var service = {};
var baseUrl = 'http://someAPI/ ';
var _query = '';
var _finalUrl = '';
var makeUrl = function() {
_finalUrl = baseUrl + _query;
}
service.setQuery = function(query) {
_query = query;
}
service.getQuery = function() {
return _query;
}
service.callBooks = function() {
makeUrl();
var deffered = $q.defer();
$http({
url: _finalUrl,
method: "GET"
}).success(function(data, status, headers, config) {
deffered.resolve(data);
}).error(function(data, status, headers, config) {
deffered.reject
})
return deffered.promise;
}
return service;
});
And the controller is:
app.controller('StoreController', ['BookFactory',function(BookFactory) {
var store = this;
store.products = [];
this.submitQuery = function(param) {
BookFactory.setQuery(param);
BookFactory.callBooks()
.then(function(data){
store.products = data;
}, function (data) {
alert(data);
});
}
}]);
Home.html when I call the method as follows:
ng-repeat="product in store.submitQuery('php')"
This causes an infinite loop and I can’t understand why, but if I change a bit the controller in the following way:
app.controller('StoreController', ['BookFactory',function(BookFactory) {
var store = this;
store.products = [];
this.submitQuery = function(param) {
BookFactory.setQuery(param);
BookFactory.callBooks()
.then(function(data){
store.products = data;
}, function (data) {
alert(data);
});
}
this.submitQuery('php');
}]);
The difference is that in the controller submitQuery is called
Than in home.html:
ng-repeat="product in store"
Things are going well but I wish thought the през view to pass different parameters.
Thanks in advance.

ng-repeat="product in store.submitQuery('php')"
of course this will make infinite loop ,cause when you make request,ng-repeat is redrawing and invoke same query over and over,
in order to pass diffrent param for query you can bind any variable to view
html
<input ng-model="queryParam" />
controller
app.controller('StoreController', ['BookFactory','$scope',function(BookFactory,$scope) {
var store = this;
$scope.store.products = [];
$scope.queryParam="php";
this.submitQuery = function() {
var param=$scope.queryParam;
BookFactory.setQuery(param);
BookFactory.callBooks()
.then(function(data){
store.products = data;
}, function (data) {
alert(data);
});
}
this.submitQuery();
}]);
and you can set up value of input and thus pass query param to contoller

Thanks for your answer
Not only in ng-repeat is happening. I mean, even if store.submitQuery('php') executes without ng-repeat, the result will be the same (infinity loop).
However for me from semantic point of view to use additional html element for this is not very good.
I changed the view like this:
<div ng-init="store.init('php')" ng-controller="StoreController as store">
{{store}}
</div>
And little bit the controller:
app.controller('StoreController', ['BookFactory',function(BookFactory) {
var store = this;
store.products = [];
this.init = function(param) {
BookFactory.setQuery(param);
this.submitQuery();
}
this.submitQuery = function(param) {
BookFactory.callBooks()
.then(function(data){
store.products = data;
}, function (data) {
alert(data);
});
}
}]);
And now it’s working like I need, but I’m not sure this is the right way.

Related

Load first json object by default - Angular

I'm hoping this is an easy question to answer...
I'm trying to create a table that loads my json, then be able to click a row and load more details that pertain to the json object. When you click a row it should load additional details at the top of the page. The row clicking part is working fine. What I'm having trouble with is loading the initial object by default.
Below is an example of what I'm referring to:
var myItemsApp = angular.module('myItemsApp', [ ]);
myItemsApp.factory('itemsFactory', ['$http', function($http){
var itemsFactory = {
itemDetails: function () {
return $http({
url: "fake-phi.json",
method: "GET",
}).then(function (response) {
return response.data;
});
}
};
return itemsFactory;
}]);
myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory',
function($scope, itemsFactory){
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
console.log(data);
});
$scope.select = function (item) {
$scope.selected = item;
}
}]);
http://embed.plnkr.co/6LfAsaamCPPbe7JNdww1/
I tried adding this after $scope.select, but got an error:
$scope.selected = item[0];
How do I get the first object in my json to load by default?
thanks in advance
Inside your promise resolve function assign the first item of the array, as a selected value:
promise.then(function (data) {
$scope.itemDetails = data;
$scope.selected = data[0];
console.log(data);
});
var myItemsApp = angular.module('myItemsApp', [ ]);
myItemsApp.factory('itemsFactory', ['$http', function($http){
var itemsFactory = {
itemDetails: function () {
return $http({
url: "fake-phi.json",
method: "GET",
}).then(function (response) {
return response.data;
});
}
};
return itemsFactory;
}]);
myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory',
function($scope, itemsFactory){
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
$scope.selected = data[0];
console.log($scope.itemDetails);
console.log($scope.selected);
});
}]);

$scope not being acessed in the view

I'm using Angular in an application. After getting a specific object (a movie in my case), I'm assigning the object to $scope ($scope.movie = response), so that I can use it in the view. The problem is that my view seems not to display anything I use in $scope. I've tried deleting everything and doing a dummy test like $scope=name="whatever" and when I use something like {{name}} in the view nothing is rendered. Have anyone faced this problem ? I've already searched for this error, and it seems like it would be a good idea to use $apply(). I've tried that and it didn't work. The function that fetches the data is below:
var app = angular.module('movies');
app.factory('Films', ['$resource',function($resource){
return $resource('/films.json', {},{
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
})
}]);
app.factory('Film', ['$resource', function($resource){
return $resource('films/:id.json', {}, {
show: {method: 'GET' },
update: { method: 'PUT', params: {id: '#id'} },
delete: { method: 'DELETE', params: {id: '#id'} }
});
}]);
app.controller('MoviesController', ['$scope', '$http', '$location', '$resource', '$routeParams', 'Films', 'Film', function($scope, $http, $location, $resource, $routeParams, Films, Film){
$scope.movies = Films.query();
$scope.user = document.getElementById('name').innerHTML; // Find a better way to interact with devise via angular
$scope.createMovie = function() {
$scope.movies = Films.query();
$http.get(
'/categories.json'
).success(function(data,status,headers,config){
$scope.categories = data;
}).error(function(data, status, headers, config){
alert("There was an error while fetching the categories on the database. Error " + status);
});
$location.path("/" + 'new').replace();
};
$scope.listMovies = function() {
$location.path("/").replace();
};
$scope.save = function(){
if($scope.form.$valid){
Films.create({film: $scope.movie}, function(){
$scope.form.$setPristine();
}, function(error){
alert("Movie not created");
});
}
};
$scope.deleteMovie = function(movie){
Film.delete(movie);
$scope.movies = Films.query();
};
$scope.viewDetails = function(movie){
$scope.name="ola";
alert(movie.id);
$location.path("/" + movie.id);
var Movie = $resource('films/:filmId'+'.json', {filmId: '#id'});
$scope.movie = Movie.get({filmId: movie.id});
$scope.movie.$promise.then(
function(response){
$scope.$apply();
$scope.movie = response;
console.log("filme e: " + response.name);
},
function(error){
console.log("request failed");
}
);
};
}]);
I had a look at your repository and I think where your problem is. You are trying to reuse the MoviesController in all of your routes. But AngularJS will create a new instance for every route and therefore you can't access your previous data because it will be destroyed.
So I would start by creating a separated controller for each view, so you can move the code of your viewDetails method to a new MovieDetailController. To have access to the movie id in this controller, you need to use the $routeParams service.
angular.module('movies').controller('MovieDetailController', MovieDetailController);
function MovieDetailController($scope, $resource, $routeParams) {
var Movie = $resource('films/:filmId'+'.json', {filmId: '#id'});
Movie.get({filmId: $routeParams.id}).then(
function(response) {
$scope.movie = response;
},
function(error){
console.log('request failed');
}
);
}
Change your route definition to use the new controller.
.when('/movies/:id', {
controller: 'MovieDetailController',
templateUrl: 'movie_details.html'
})
And now your viewDetails method in the MoviesController just need to redirect to the movie detail url.
$scope.viewDetails = function(movie) {
$location.path('/movies/' + movie.id);
}
I hope it works for you. Let me know when you try!

Passing Service data from module config to Controller from $routeProvider?

I am really new to angular and have been reading a number of tutorials etc and have the following problem:
search-module.js
var Search = angular.module('SearchApp',["ngCookies","ngRoute"]);
Search.run(function ($http, $cookies) {
$http.defaults.headers.common['X-CSRFToken'] = $cookies['csrftoken'];
});
Search.config(function($routeProvider){
$routeProvider
.when('/', {
controller:'searchCtrl',
resolve: {
inv_items: function (InventoryService){
return InventoryService.get('red');
}
}
})
.otherwise({
redirectTo: '/'
})
});
data-service.js
Search.factory('InventoryService', function ($http, $q) {
var api_url = "api/inventory/";
return {
get: function (inventory) {
var url = api_url + inventory;
var defer = $q.defer();
$http({method: 'GET', url: url}).
success(function (data, status, headers, config){
defer.resolver(data);
})
.error(function (data,status, headers, config){
defer.reject(status);
});
return defer.promise;
}
}
});
search-controller.js
Search.controller('searchCtrl', function($scope){
$scope.selected = 'have';
$scope.setSection = function(section){
$scope.selected = section;
};
$scope.isSelected = function(section){
return $scope.selected == section;
};
});
Like I mentioned previously I am really new to angular just picked it up yesterday. Basically from what I have written I understand that when the URL is '/' then the service will be initiated and the controller will be called? What I want to know is why cant I use inv_items in my controller? I get the following error.
Do I need to pass some sort of global to the controller which will contain inv_items or am I missing some important piece of knowledge?
Thanks!
The resolve variable 'inv_items' isn't automatically added to your scope of 'searchCtrl'.
Search.controller('searchCtrl', function($scope, inv_items){ //Add this
$scope.inv_items = inv_items; //And this
$scope.selected = 'have';
$scope.setSection = function(section){
$scope.selected = section;
};
$scope.isSelected = function(section){
return $scope.selected == section;
};
});
Granted that the rest of the code works, your 'inv_items' should now be available in that scope.

load jsonp into multiple AngularJS controllers

I have a jsonp call to a server which returns an object containing two objects.
At the moment I make the jsonp call with jQuery because I've just started learning AngularJS and I dont know how it's done.
I want to use data.filters in navController and data.results in contentController
What would be the correct way to achieve this with AngularJS ?
(function($, angular) {
$(function() {
$.ajax({
jsonp: "JSONPCallback",
url: 'myUrl',
dataType: 'jsonp',
success: function(data) {
//data = {"filters":{...},"results":{...}}
}
});
});
var app = angular.module('app', []);
var controllers = {};
controllers.navController = function($scope) {
$scope.filters = [{}];
};
controllers.contentController = function($scope) {
$scope.results = [{}];
};
app.controller(controllers);
})(jQuery, angular);
Hi please see here http://plnkr.co/edit/hYkkQ6WctjhYs8w7I8sT?p=preview
var app = angular.module('plunker', []);
app.service('dataService', function($http){
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
var dataReady= false
var filters = [];
var results = [];
function getData() {
if (dataReady)
retrun
else
{
$http.jsonp(url)
.success(function(data){
//in your case
//angular.copy(data.filters, filters)
//angular.copy(data.results , results )
angular.copy(data.posts[0], results);
angular.copy(data.posts[1], filters);
dataReady = true
}).error(function(){
alert('cant load data');
});
}
}
return {
filters : filters,
results : results,
getData : getData
}
})
app.controller('MainCtrl', function($scope,dataService) {
$scope.name = 'World';
$scope.items = dataService.results;
dataService.getData();
});
app.controller('SecondCtrl', function($scope,dataService) {
$scope.filters = dataService.filters;
dataService.getData();
});

AngularJS binding service variable to controller

I am a Angular noob and having problems with binding a variable from one of my services to one of my controllers. I have read at least a dozen posts on the subject and nothing seems to be working for me.
Here is the controller:
app.controller('TeamController', ['$scope', '$modal', 'teamService', function ($scope, $modal, teamService) {
$scope.teamService = teamService;
$scope.selectedTeam = null;
$scope.selectTeam = function(teamId){
$scope.selectedTeam = teamService.getTeam(teamId, $scope.login.loginId);
};
}]);
Here is the service:
angular.module('teamService', [])
.service('teamService', function($http, $q){
this.selectedTeam = {teamId:-1, teamName:"Select a team", teamLocationName:"", teamDescription:"", teamManaged:false};
this.userTeams = [];
this.getTeam = function(teamId, loginId) {
var postData = {teamId: teamId, loginId: loginId};
var promise = $http({
url: "/url-for-getting-team",
method: "POST",
data: postData
});
promise.success(function (data) {
if (data.status === "success") {
this.selectedTeam = data.response;
return data.response;
}
});
promise.error(function () { //TODO handle getTeam errors
return {};
});
};
this.getSelectedTeam = function(){
return this.selectedTeam;
};
});
And here is the template:
<div class="jumbotron main-jumbo" ng-controller="TeamController">
<h1>{{selectedTeam.teamName}}</h1>
</div>
I have tried binding to the getSelectedTeam function and the service variable itself. Do I need to set up a $watch function in the controller? Any assistance would be greatly appreciated.
EDIT:
I tried turning my service into a factory, which still did not help me, so then I looked at a provider that was properly working that I had already written in the application. I converted my "teamService" into a provider and finally worked like a charm. Thanks for the contributions guys.
Code from my new provider:
angular.module('teamService', [])
.provider('teamService', function () {
var errorState = 'error',
logoutState = 'home';
this.$get = function ($rootScope, $http, $q, $state) {
/**
* Low-level, private functions.
*/
/**
* High level, public methods
*/
var wrappedService = {
/**
* Public properties
*/
selectedTeam: {teamName:"Select a team"},
userTeams : null,
createTeam: function(loginId, name, description, locationName, managed){
var postData = {loginId:loginId, teamName:name, teamDescription:description, teamLocationName:locationName, teamManaged:managed};
var promise = $http({
url: "/create-team-url",
method: "POST",
data: postData
});
return promise;
},
getTeam: function(teamId, loginId) {
var postData = {teamId: teamId, loginId: loginId};
var promise = $http({
url: "/get-team-url",
method: "POST",
data: postData
});
promise.success(function (data) {
if (data.status === "success") {
wrappedService.selectedTeam = data.response;
}
});
promise.error(function () { //TODO handle getTeam errors
wrappedService.selectedTeam = {};
});
},
getUserTeams: function(loginId) {
var postData = {loginId: loginId};
var promise = $http({
url: "/team-list-url",
method: "POST",
data: postData
});
return promise;
},
joinTeam: function(teamId, loginId){
var postData = {teamId:teamId, loginId:loginId};
var promise =$http({
url: "/join-team-url",
method: "POST",
data: postData
});
return promise;
},
getSelectedTeam: function(){
return wrappedService.selectedTeam;
}
};
return wrappedService;
};
});
As seen in my edit. I converted my service into a provider and all the changes seem to propagate to the view with no issues. I need to further analyze the difference between the factory, service, and provider in order to gain a higher understanding of what is going on here.
The main issue with the code is the way that promises are used. You can either correct that within the service, or handle it in the controller. As an example of the latter, you can re-write the above as:
Controller Code:
app.controller('TeamController', ['$scope', '$modal', 'teamService', function ($scope, $modal, teamService) {
$scope.teamService = teamService;
$scope.selectedTeam = null;
$scope.selectTeam = function(teamId){
teamService.getTeam(teamId, $scope.login.loginId).then(
function(result){
$scope.selectedTeam = result.data;
},
function(error){
console.log(error);
}
)
};
}]);
Service code:
angular.module('teamService', [])
.service('teamService', function($http, $q){
this.selectedTeam = {teamId:-1, teamName:"Select a team", teamLocationName:"", teamDescription:"", teamManaged:false};
this.userTeams = [];
this.getTeam = function(teamId, loginId) {
var postData = {teamId: teamId, loginId: loginId};
return $http({
url: "/url-for-getting-team",
method: "POST",
data: postData
});
};
this.getSelectedTeam = function(){
return this.selectedTeam;
};
});
You can also handle this in the service itself, but it requires a little more code. The key thing is that the getTeam call is asynchronous and needs to be handled using proper promise constructs.

Resources