AngularJS factory and controller code, not producing anything - javascript

When the below code is run nothing shows in my console to indicate anything went wrong, but as you can see in listService it's alerting withing the results, but the alert shows as "undefined".
I'm ultimately trying to get it to run a repeat to list all the Organizations on the view. Any help is appreciated!!
Here is my factory.
app.factory("listService", ["$rootScope", "$http", "$location", "$routeParams",
function($rootScope, $http, $location, $routeParams) {
var siteURL = "jdfyhgyjdfghyjdgfyhkjyhjk";
var svc = {};
var data = null;
svc.getListItems = function(listName) {
$http({
url: siteURL + "/_api/web/lists/GetByTitle('" + listName + "')/items",
method: "GET",
async: false,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
},
success: function(response, status, headers, config) {
data = response.data.d.results;
alert(data);
},
error: function(response, status, headers, config) {
$rootScope.error = status;
}
});
}
return svc;
}
]);
Here is my controller.
app.controller("readOrganizationsCtrl", ["$scope", "$http", "$location", "$routeParams", "listService",
function($scope, $http, $location, $routeParams, listService) {
$scope.organizations = listService.getListItems('Organizations');
}
]);
And lastly here is my view.
<div class="form-group">
<input type="text" class="form-control" id="search" placeholder="Search organizations" data-ng-model="search" />
</div>
<table class="table table-stripped table-hover">
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="organization in organizations | filter:search" data-ng-click="editOrganization($index)">
<td>{{organization.Title}}</td>
</tr>
</tbody>
</table>
<div class="form-group">
<button data-ng-click="addOrganization()" class="btn btn-primary">Add Organization</button>
</div>
{{"Error:" + error}}

after calling $http in controller you can easily get all your organizations from siteURL, here is working code:
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$http({
method: 'GET',
url: 'organizations.json',
headers: {
withCredentials: true,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
},
})
.then(function successCallback(data) {
$scope.organizations = data.data;
console.log($scope.organizations)
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
});
HTML:
<tbody>
<tr data-ng-repeat="organization in organizations | filter:search" data-ng-click="editOrganization($index)">
<td>{{organization.name}}</td>
</tr>
</tbody>
plunker: http://plnkr.co/edit/aP7fLU1tfWwmZdCAYzIf?p=preview
Or, if you want to do it by factory, you can do it this way:
app.controller('MainCtrl', function($scope, $http, factory) {
factory.getOrganizations()
.then(function(data){
$scope.organizations = data.data;
console.log($scope.organizations)
})
.catch(function(){
})
});
app.factory('factory',function($http){
return {
getOrganizations: function(){
return $http.get('organizations.json');
}
};
})
plunker: http://plnkr.co/edit/UJUrTIGHGtjjccGAnHlk?p=preview

Related

$http not defined when posting to server

Here's my json:
[
{
"name": "AAAAAA",
"date": "28-03-2016",
},
{
"name": "BBBBBB",
"date": "20-12-2016",
},
{
"name": "CCCCCC",
"date": "09-01-2016",
},
{
"name": "DDDDDD",
"date": "21-07-2016",
}
]
My javascript:
var app = angular.module('app', []);
app.service('service', function($http, $q){
var deferred = $q.defer();
$http.get('names.json').then(function(data){
deferred.resolve(data);
});
this.getNames = function() {
return deferred.promise;
}
});
app.controller('FirstCtrl', function($scope, service) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.data;
console.log($scope.names);
}
);
$scope.postfunction = function() {
$http({
method: 'POST',
url: 'serverUrl',
data: name.name,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
};
});
My HTML:
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.time | date}}</td>
<td><button ng-click="postfunction()">POST</button></td>
</tr>
</tbody>
What I want do is when I click the button "POST" name.name post to server. I try $http.post in postfunction(), but I get "$http is not defined" in console.
You forgot to inject $http into your controller
app.controller('FirstCtrl', function($scope, service, $http) {
^
You have to inject $http service in your controller 'FirstCtrl' as below:
app.controller('FirstCtrl', function($scope, service, $http) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.data;
console.log($scope.names);
}
);
$scope.postfunction = function(name) {
$http({
method: 'POST',
url: 'serverUrl',
data: name,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
};
});
Also additionally along with passing the argument to the post function, you have to pass the 'name' in the HTML as below, this is because, in your controller, 'name' is never defined.
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.time | date}}</td>
<td><button ng-click="postfunction(name.name)">POST</button></td>
</tr>
</tbody>

data not getting populated to the view from controller after routing in angular

I am seeing no data in my view (Html) . where as i am getting data into controller from service as well.
Please let me know what i am missing .
Any suggestions what i am missing
Controller:
(function () {
'use strict';
angular.module('app') .controller('UserController', UserController);
UserController.$inject = ['$scope', 'UserService', '$http', '$filter', '$rootScope','$location','$window'];
function UserController($scope, UserService, $http, $filter, $rootScope,$location,$window) {
$scope.editUser = function(userDetails){
UserService.editUser(userDetails).then(editUserSuccess,editUserFailure);
$location.path('edit');
}
var editUserFailure =function (error){
};
var editUserSuccess = function (response) {
var userRow = response.data;
$scope.edituserData=userRow;
};
};
})();
This is my service part
(function () {
'use strict';
angular.module('app').factory('UserService', UserService);
UserService.$inject = ['$http', '$rootScope'];
function UserService($http, $rootScope) {
var service = {};
service.editUser = editUser;
return service;
function editUser(editUserObj){
console.log(editUserObj.userId);
return $http({
method: 'POST',
url: 'editUser',
data: btoa(editUserObj.userId),
contentType: "application/json; charset=utf-8",
});
}
}
})();
My routing from application
appname.config(function($routeProvider) {
$routeProvider
.when("/edit", {
templateUrl:"my.html",
controller : 'UserController'
});
});
my.html:
--------
When i am trying to get data in my html template
<div class="row">
<div class="col-lg-6 col-sm-6 col-xs-6">
<p class="text-right"><strong>Middle Name :</strong></p>
</div>
<div class="col-lg-6 col-sm-6 col-xs-6">
<p class="text-left-user"> {{editUserData.screenName}}</p>
</div>
</div>
Thanks in advance
Your service just needs to return the data on success. Right now it is only returning the Promise.
(function () {
'use strict';
angular.module('app').factory('UserService', UserService);
UserService.$inject = ['$http', '$rootScope'];
function UserService($http, $rootScope) {
var service = {};
service.editUser = editUser;
return service;
function editUser(editUserObj){
console.log(editUserObj.userId);
return $http({
method: 'POST',
url: 'editUser',
data: btoa(editUserObj.userId),
contentType: "application/json; charset=utf-8",
}).success(function(response){
return response;
});
}
}
})();
Then in your .then success function in the controller, you should have the response available.

User Based Login Page in AngularJS

Iam creating an angular app, in which the data will be displayed based on the user details entered in login page.
In brief, I need help in acheiving the below:
When user enters username and Password, url will be built with these username and password and url will be called so that an unique id(a numeric digit) will be generated for each user. This unique id will be in a JSON format like {"Record":[{"Id":12}]}
Now if the unique id is returned from url, tab.html has to be displayed or if null is returned, an error message of wrong credentials has to be displayed.
For a successfully loggedin user, a table in tab.html will be displayed based on uniqueid which is generated from username and password.
Below is the code I have:
login.html:
<form ng-submit=submit()>
<input type="text" name="username" placeholder="Username" ng-model="person.firstName" required />
<span class="error" ng-show="mainForm.usernamename.$error.required">required</span>
<input type="password" name="pswd" placeholder="Password" ng-model="person.pswd" required />
<span class="error" ng-show="mainForm.pswd.$error.required">required</span>
<div class="submit">
<div>
<label>
<input name="remember" type="checkbox" data-ng-model="remember" data-ng-click="rememberMe()"> Remember Me
</label>
</div>
<input type="submit" value="LOGIN">
</div>
<div class="row">
<div class="col-sm-10"><p>Forgot Password?</p></div>
</div>
</form>
tab.html:
<div ng-controller="SampleController">
<table class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th>Name</th>
<th>ID</th>
<th>Qualification</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in tableContent" >
<td>{{x.Name}} </td>
<td>{{x.DT}}</td>
<td>{{x.Qualification}}</td>
</tr>
</tbody>
</table>
</div>
app.js:
var wc = angular.module('wc', []);
wc.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/login');
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
.state('tab', {
url: '/tab1',
templateUrl: 'views/tab.html'
});
});
wc.controller('LoginCtrl', function ($scope,$http, $location) {
$scope.submit = function () {
$http.get("URL-PartAame=" + $scope.person.firstName + "&Password=" + $scope.person.pswd)
.success(function (data) {
//how to get the id from above url and display data based on condition//
$scope.tableData = data;
console.log(data)
$location.path('/tab1');
})
.error(function (response, status, headers, config) { });
}
});
wc.controller('SampleController', function ($scope, $http, $modal) {
$http.get("UrlA-UserId="returnedId)
.success(function (response) {
$scope.tableContent = response.Table;
});
};
I understood that this can be solved by using service or factory, but here how can a service be called along with the submit()? If this is not the correct way, please suggest the other way of doing it. Thanks in advance!!
Using $state.go and $stateParams service.
wc.controller('LoginCtrl', function ($scope,$http, $location, $state) {
$scope.submit = function () {
$http.get("URL-PartAame=" + $scope.person.firstName + "&Password=" + $scope.person.pswd)
.success(function (data) {
//how to get the id from above url and display data based on condition//
$scope.tableData = data;
console.log(data)
$state.go('tab', {id: the_necesarry_id});
//$location.path('/tab1');
})
.error(function (response, status, headers, config) { });
}
});
wc.controller('SampleController', function ($scope, $http, $modal, $stateParams) {
var returnedId = $stateParams.id;
$http.get("UrlA-UserId="returnedId)
.success(function (response) {
$scope.tableContent = response.Table;
});
};
Notice that you need add the id property contained in the $stateParams service in your url state.
.state('tab', {
url: '/tab1/:id',
templateUrl: 'views/tab.html'
});

pass an ID to next page after clicking a link in angularjs

I have a list of places that I am printing list of places, and the idea is when the user clicks on the place it takes the user to another page where the details of the place can be viewed. How can I achieve this?
HTML:Page1
<li ng-repeat="place in places.places">
{{place.name}}
</li>
Page2:
<table ng-controller="UncatCtrl">
<tr>
<td>Name: </td><td>{{place.place.name}}</td>
</tr>
<tr>
<td>placeID: </td><td ng-model="PlaceID">{{place.place.placeID}}</td>
</tr>
</table>
Angular:
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/uncatdetails', {
templateUrl: 'templates/uncatpost.html',
controller: 'UnCatPostCtrl'
})
}])
.controller('UnCatPostCtrl', function ($scope, $http) {})
.controller('UncatCtrl', function ($scope, $http) {
$http.get('http://94.125.132.253:8000/getuncategorisedplaces').success(function (data, status, headers) {
$scope.places = data;
console.log(data);
$scope.message = 'Uncategorised places';
})
$scope.showplace = function(placeID) {
$http({method: 'GET', url: 'http://94.125.132.253:8000/getitemdata?ID=' + placeID}).
success(function(data, status, headers, config) {
$scope.place = data; //set view model
console.log(data);
console.log(placeID);
$scope.view = 'templates/detail.html';
})
.error(function(data, status, headers, config) {
$scope.place = data || "Request failed";
$scope.status = status;
$scope.view = 'templates/detail.html';
});
}
})
try it
.when('/uncatdetails/:id', {templateUrl: 'ftemplates/uncatpost.html',
controller: 'UnCatPostCtrl'})
in your HTML
ng-href="uncatdetails/{{place.placeID}}"
in your controller, add this inject $routeParams
$scope.id = $routeParams.id;

AngularJS $scope in a factory

Is it possible to use a scope in a factory then using it on multiple controllers ?
I'm not really up to writing the same code in every controller, it'll be a pain to work on it ^^
Here's my current idea.
.factory('FactoryName', function($scope, $routeParams, $http) {
return {
search : function(str, http) {
var url = str+'.json';
return $http.get(url).success(http).error(function() {
alert('Unable to get back the data');
});
}
httpSuccessPaper : function(response) {
$scope.papers = response;
}
This way I only have this code once and all my controller are able to use the json of "reference". I could also write something like ng-repeat="p in papers" in some view.
Here is the way I call it in my controller :
.controller('CtrlName', ['$scope', '$routeParams', '$http', 'FactoryName'
function($scope, $routeParams, $http, FactoryName) {
FactoryName.search("Paper",FactoryName.httpSuccessPaper).then(function(){
$scope.paper = getByIdPa($scope.papers,$routeParams.id);
})
It seems a bit strange to me and I'm almost sure I'm trying something impossible.
I would like your opinion.
Thank you !
you can do it like this:
angular.module('apiServices', ['ngResource'])
.factory('ExampleService', ['$http', 'serviceUrl', function ($http, serviceUrl) {
return{
getInteractions: function () {
return $http({method: 'GET', url: serviceUrl + 'ctest', headers: {'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache', 'Expires': '0'}});
},
getRoots: function () {
return $http({method: 'GET', url: serviceUrl + 'ntest', headers: {'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache', 'Expires': '0'}});
},
getLogging: function (params) {
return $http.post(serviceUrl + 'atest', params);
},
getMessage: function (params) {
return $http({method: 'GET', url: serviceUrl + 'btest', params: params, headers: {'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache', 'Expires': '0'}});
}
};
}]);
You don't want Services dealing with scopes. It's ok to repeat just the setting the scope part.
.factory('FactoryName', function($scope, $routeParams, $http) {
return {
search : function(str) {
var url = str+'.json';
return $http.get(url)
}
Then the controller:
.controller('CtrlName', ['$scope', '$routeParams', '$http', 'FactoryName'
function($scope, $routeParams, $http, FactoryName) {
FactoryName.search("Paper").then(function(papers){
$scope.paper = getByIdPa($papers,$routeParams.id);
})

Categories

Resources