displaying data ng-repeat from $scope.items query not working - javascript

I do not know what is wrong, ng-repeat is not
populating the information on my div, please look at the following
and advice where I have gone wrong
app.js
var mainApp = angular.module('mainApp', ["ngRoute", "ngResource"]);
mainApp.factory('EventListFactory',['$resource', EventListFactory]);
mainApp.controller('EventListCtrl', ['$scope','EventListFactory', EventListCtrl]);
var configFunction = function ($routeProvider) {
$routeProvider.
when('/Register', {
templateUrl: 'routesDemo/Register'
})
.when('/UpdateProfile', {
templateUrl: 'routesDemo/UpdateProfile'
})
.when('/Events', {
templateUrl: 'routesDemo/Events',
controller: EventListCtrl,
})
.when('/routeThree', {
templateUrl: 'routesDemo/three'
});
}
configFunction.$inject = ['$routeProvider'];
mainApp.config(configFunction);
EventListFactory.js
var EventListFactory = function ($resource, $location) {
var baseUrl = "";
if (window.location.hostname == 'localhost') {
baseUrl = "http://localhost:52182/api/Events/GetEvents/";
}
else
{
var deployAt = window.location.href.substring(0, window.location.href);
baseUrl = deployAt + "/api/Events/GetEvents";
}
var respone = $resource(baseUrl, null, { query: { method: 'GET', isArray: true, url: baseUrl }, get: { method: 'GET', url: baseUrl } });
console.log("api json at :" + baseUrl);
var records = respone.query();
console.log(records);
return records;
}
EventListController.js
var EventListCtrl = function ($scope, EventListFactory) {
$scope.Message = 'I work';
$scope.items = EventListFactory;
};
EventListCtrl.$inject = ['$scope'];
in the html:
<div id="listView" >
<h1 class="form-signin-heading">For real {{Message}}</h1>
<div ng-controller="EventListCtrl">
<p class="form-signin-heading">Populated Data</p>
<div ng-repeat="item in items ">
<span class="control-label">Heading : </span> {{item.Heading}}
<br/>
<span class="control-label">Event Date : </span> {{item.EventDate}}
<br/>
</div>
</div>
</div>
running the site:
api call from browser:

the code for ng-repeat is correct, but your items is an empty array so nothing gets displayed.
From the screenshots it appears that records in EventListFactory.js does not return an array but a promise.
In EventListController.js instead of
$scope.items = EventListFactory;
Try something like:
var promise = EventListFactory;
promise.then(function(data){
$scope.items = data;
})

Related

API, angularJS, to get datas

I never done angularJS from all my life and i am lost.
So i have done this file, to obtain datas from an api with a filter of time.
forecast.js
(function() {
angular.module('application').factory('Forecast', ['$http', '$q', function($http, $q){
var ApiAddr = "api.com/";
forecast.getResults = function(timeStart, timeEnd){
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiAddr, {
params: httpParams,
cache: true
}).then(function(data){
return data;
},
function(response){
console.log(
"HTTP request "+ApiAddr+
" (with parameters tsmin="+httpParams.tsmin+", tsmax="+httpParams.tsmax+
", type="+httpParams.type+", time="+httpParams.time+
(httpParams.motive ? ", motive="+httpParams.motive : "")+
(httpParams.vector ? ", vector="+httpParams.vector : "")+
(httpParams.media ? ", media="+httpParams.media : "")+
") failed with "+response.status
);
return $q.reject(response);
}
);
}];
But i have no idea to make a controller adapter to this. What type of controller i can do ?
Every exemple are based on a fixed json file, with no parameters.
Moreover, i want, in HTML to imput the time filter, but i have totaly no idea of what to do for this. The example i have seen were to get datas, no to send.
Ps : I have made 2 days of research about this, i have never done front end programming in my life.
(function() {
angular.module('application', [])
.factory('Forecast', ['$http', '$q', function($http, $q) {
var apiaddress = 'api.com';
var forecast = {};
forecast.getResults = function(timeStart, timeEnd) {
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiaddress, {
params: httpParams,
cache: true
}).then(function(result) {
return result.data;
});
};
return forecast;
}])
.controller('SampleCtrl', ['$scope', 'Forecast', function($scope, Forecast) {
$scope.forecastReport = '';
$scope.getForecast = function() {
Forecast.getResults($scope.timeStart, $scope.timeEnd)
.then(function(report) {
$scope.result = report;
}).catch(function(err) {
$scope.result = '';
console.error('Unable to fetch forecast report: ' + err);
});
};
}]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="application" ng-controller="SampleCtrl">
<label>Time Start:
<input type="text" ng-model="timeStart"/></label>
<label>Time End:
<input type="text" ng-model="timeEnd"/></label>
<button ng-click="getForecast()">Get Forecast</button>
<hr/>
<div>
<b>Forecast Result:</b>
</div>
<pre>{{forecastReport | json}}</pre>
</div>
Just inject the factory into your controller like this:
var app = angular.module('application');
app.controller('myController',
['$scope', 'Forecast', function($scope, Forecast) { /* access to Forecast*/}]);
Or with a component (cleaner):
app.component('myComponentCtrl', {
templateUrl: 'template.html'
controller: myComponentCtrl
})
myComponentCtrl.$inject = ['$scope', 'Forecast'];
function myComponentCtrl($scope, Forecast) {/* ... */ }

Detail Page View not Showing Data in ionic

I'm new to Ionic. I write code for list. List is working perfectly but when click on any list-item it's not showing any data.
It showing me this error "Cannot GET /pilliondetails/1" how can i solve this?
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
console.log(savedData);
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
})
PillionList Controller:
.controller('PillionListCtrl',function($scope,$ionicHistory,myService){
$scope.myGoBack = function() {
$ionicHistory.goBack();
};
$scope.pillions = [];
var promise=myService.get();
$scope.pillions=myService.get();
})
PillionDetail Controller:
.controller('PillionDetailCtrl',function($scope, $ionicHistory, $stateParams, myService)
{
$scope.myGoBack = function() {
$ionicHistory.goBack();
};
var promise=myService.get($stateParams.requestId);
console.log(promise);
})
PillionList.html :Showing list pf Pillions
<ion-list>
<ion-item data-ng-repeat="pillion in pillions">
<div class="list list-inset">
{{pillion.request_departure_date}}-{{pillion.request_departure_time}}
{{pillion.request_from}} >> {{pillion.request_to}}
{{pillion.user_first_name}} {{pillion.user_last_name}}
<a ui-sref="pilliondetails({pillionId:pillion.request_id})" nav-direction="enter">
<h2>More Details...</h2>
</a>
</div>
</ion-item>
</ion-list>
my app.js
.state('pillionlist', {
url: '/pillionlist',
templateUrl: 'templates/pillionlist.html',
controller: 'PillionListCtrl'
})
.state('pilliondetails', {
url: '/pillionlist/:pillionId',
templateUrl: 'templates/pilliondetails.html',
controller: 'PillionDetailCtrl'
})
Its redirecting to pillionDetail view but not showing data.
Please help.
The first thing i noticed is
ui-sref="pilliondetails({pillion.request_id})"
it should be key-value pair like this
ui-sref="pilliondetails({ your_id : pillion.request_id})"
and in stateProvider, the url of details page should contain parameter. for eg.
url : '/pilliondetails/:your_id'

typeahead fetch data from url key and api angularjs

Hi I am new to Angularjs. I am trying to create a typeahead where I am fetching the data through the api. I tried searching for the solution but I dint get the solution what I was looking for. Below is the code what I have done so far.
HTML CODE:
<div ng-controller="newController">
<div class="selection-box">
<div class="title-box">
<div class="search_item">
<input name="document" ng-model='query' type="text" typeahead="document as document.name for document in documents | filter:query | limitTo:8" id='document' placeholder="SEARCH FOR YOUR DOCUMENT" class="search_box">
</div>
{{query}}
</div>
</div>
</div>
In this input box whatever I type it gets printed in the {{query}} but doesn't show any data fetching from the api. I am using bootstrap ui . Below is the controller what I wrote.
newController.js:
var myApp = angular.module('myModule', ['ui.bootstrap']);
myApp.service("searchService", function ($http) {
var apiUrl = "http://12.56.677/api/v1/mobile/";
var apiKey = "123nm";
this.searchDocument = function(query) {
var response = $http({
method: 'post',
url: apiUrl + "search",
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
params: {
key: apiKey,
query: query
}
});
return response;
};
});
myApp.controller('newController', ['$scope', 'searchService' , function($scope, searchService, $rootScope, $http, $window, $document) {
var apiUrl = "http://12.56.677/api/v1/mobile/";
var apiKey = "123nm";
url = apiUrl + "search";
Key = apiKey;
$scope.query = undefined;
console.log(query);
searchService.searchDocument(query='').then (function (res) {
if(res.data.status == "OK")
{
$scope.documents = res.data.result;
console.log($scope.documents);
// var userinformation = res.data.result;
// $window.localStorageService.setItem('searchDocument', JSON.stringify(query));
}
else {
$scope.errorMessage = res.data.message;
}
})
}])
Any help would be appreciated.
What you attempted to do is using typeahead with a pre-fetched list (an with an empty query).
You probably want to do asynchronous search and would need a data fetch function to do so.
HTML, note the typeahead expression:
<input name="document" ng-model='query' type="text"
typeahead="document as document.name for document in (getDocuments() | limitTo:8)"
id='document'
placeholder="SEARCH FOR YOUR DOCUMENT" class="search_box">
Controller:
myApp.controller('newController', ['$scope', 'searchService' , function($scope, searchService, $rootScope, $http, $window, $document) {
var apiUrl = "http://12.56.677/api/v1/mobile/";
var apiKey = "123nm";
// What are these two undeclared variables lying here around for?
url = apiUrl + "search";
Key = apiKey;
$scope.getDocuments = function(query){
searchService.searchDocument(query) // Check your API, I am not sure how you're API treats these parameters
.then (function (res) {
if(res.data.status == "OK")
{
var documents = res.data.result;
console.log(documents);
return documents;
}
else {
$scope.errorMessage = res.data.message;
return [];
}
})
}
}])
I think you need to return promise from the searchService.searchDocment() as below:
return searchService.searchDocument(query='').then(......)
//HTML
<input name="document"
ng-model='query' type="text"
uib-typeahead="document as document.name
for document in documents |filter:query | limitTo:8" id='document'
placeholder="SEARCH FOR YOUR DOCUMENT" class="search_box">
//Controller
searchService.searchDocument('').then (function (res) {
if(res.data.status == "OK"){
$scope.documents = res.data.result;
}
else {
$scope.errorMessage = res.data.message;
}
});

How to refresh controller to change/refresh JSON call in AngularJS?

I am a new AngularJS learner.
My code is calling a JSON file and displays the output. However, I want the call to change the JSON call based on change in certain variable (i.e. KeyWord).
Here is the HTML part:
<body ng-controller="AppController">
<button type="button" class="btn btn-danger" ng-click="ChangeKW()">
Click to Change KeyWord
</button>
<div ng-controller="customersController as custCont" ng-model="keyWord">
KeyWord:{{ keyWord }} ==== iter:{{ iter }}
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
</body>
And here goes the Controller part:
var app = angular.module('App', []);
app.controller('AppController', function($scope, $window) {
$scope.keyWord = 3;
$scope.iter = 1;
$scope.ChangeKW = function() {
if ( $scope.keyWord === 3 )
$scope.keyWord = 1;
else
$scope.keyWord = $scope.keyWord + 1;
}
});
app.controller("customersController", function($scope, $http) {
$scope.iter = $scope.iter + 1;
$http({
url: 'test' + $scope.keyWord + '.txt',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response) {
$scope.names = response;
}).error(function(error) {
$scope.names = [{
"Name": "Errrrrrr"
}];
});
});
I want the program to load respective JSON file text1.txt, text2.txt or text3.txt based on value of KeyWord variable, which can be changed by clicking on the red button. I have defined mg-model="KeyWord" in HTML, which changes the value of {{ KeyWord }} in the output but it doesn't send refresh JSON call/output. The initial file loaded is tex3.txt (all three files can be distinguished from 1st record).
The Plunker can be found here: Plunker.
you probably need:
$scope.$watch('keyWord',function()
{
//$http call here
}
);
the ‘$watch‘ will make the $http call automatically, each time $scope.keyWord changes.
(Posted on behalf of the question author).
Here is the final solution that I found out with the help of #Manube:
HTML
<body ng-controller="AppController">
<button type="button" class="btn btn-danger" ng-click="ChangeKW()">
Click to Change KeyWord
</button>
<div ng-controller="customersController as custCont" ng-model="keyWord">
KeyWord:{{ keyWord }} ==== iter:{{ iter }}
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
</body>
This is the Controller code
(function() {
var app = angular.module('App', []);
app.controller('AppController', function($scope, $window,$http) {
$scope.keyWord = 3;
$scope.iter = 1;
$scope.ChangeKW = function() {
if ($scope.keyWord >2)
$scope.keyWord = 1;
else
$scope.keyWord = $scope.keyWord + 1;
};
$scope.loadData = function() {
$scope.iter = $scope.iter + 1;
$http({
url: 'test' + $scope.keyWord + '.txt',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response) {
$scope.names = response;
}).error(function(error) {
$scope.names = [{
"Name": "Errrrrrr"
}];
});
};
$scope.$watch('keyWord', function() {
$scope.loadData();
});
$scope.customersController = function($scope, $http) {
$scope.loadData();
};
});
})();
And a working Plunker can be found here: Plunker Link

Revealing module for AJAX Angular Service

Below I've got an angular app and controller where the controller have data access inside of it (bad idea, I know)
var app = angular.module('app',[]);
app.controller('HomeController',function($scope,$http){
$scope.people = null;
$scope.get = function() {
$http({
url: 'largeTestData.json',
method: 'GET'
}).then(function(data){
console.log('request successful, here is your data: ');
console.log(data['data']);
$scope.people = data['data'];
},function(reason){
console.log('this failed, this is the reason: ');
console.log(reason);
})
}
});
app.controller('ControllerWithService',function($scope, MyService){
$scope.get = MyService.get;
$scope.get(function(data){
console.log('you succeeded');
},function(reason){
console.log('you failed');
console.log(reason);
})
})
This will work in retrieving data and putting it onto the page. Knowing that having data Access in the controller is no bueno I tried to abstract that out into a service:
app.service('MyService',function($http,$q){
var get = function(){
var deferred = $q.defer();
var url = 'test.json';
$http.get(url).success(deferred.resolve).error(deferred.reject);
}
return {
get: get
}
})
Here my 'data layer' is a service that only has one method: get from the above listed URL.
app.service('MyService',function($http,$q){
var get = function(){
var deferred = $q.defer();
var url = 'test.json';
$http.get(url).success(deferred.resolve).error(deferred.reject);
}
return {
get: get
}
})
and my HTML
<body>
<script src="libs/angular-1.2.15.js"></script>
<script src="app/app.js"></script>
<script src="app/DocumentService.js"></script>
<script src="libs/jQuery-2.1.1.js"></script>
<div ng-controller="HomeController">
<button ng-click="get()" href="#">Get data</button>
<div>{{message}}</div>
<!--<div ng-repeat="p in people" >-->
<!--<b>Business Doc ID: </b><h1>{{p['busDocId']}}</h1>-->
<!--<b>DOC ID: </b>{{p['docId']}}-->
<!--<b>FILE NAME: </b><div style="color: green">{{p['fileName']}}</div>-->
<!--</div>-->
</div>
<div ng-controller="ControllerWithService">
{{message}}
<button ng-click="get()">get data</button>
<div>{{data}}</div>
</div>
</body>
I'm not getting any error messages, and the commented out out stuff in my HomeController works as expected. What am I doing wrong in trying to make my AJAX calls a service?
working solution changes:
app.service('MyService',function($http,$q){
this.get = function(){
return $http.get('test.json')
}
})
app.controller('ControllerWithService',function($scope, MyService){
$scope.data = null;
$scope.get = function() {
MyService.get().then(function (data) {
console.log('this is the success data: ');
console.log(data)
$scope.data = data;
}, function (reason) {
console.log('this is the fail reason');
console.log(reason);
$scope.data = reason;
})
}
})
It looks like it could be a couple different things. I'll post an example I have working in one of my projects right now. It should be extremely similar and simple with what you're goal is.
Service:
'use strict';
angular.module('srcApp')
.service('Getlanguage', function Getlanguage($location, $http, $log, $state, $rootScope) {
this.getContent = function() {
var language = $location.path().split('/'),
languageCulture = language[1];
if (!languageCulture) {
languageCulture = 'en';
}
$rootScope.cultureCode = languageCulture;
return $http({method: 'GET', url: '/languages/' + languageCulture + '.json'})
.error(function() {
// If service cannot find language json file, redirect to index
$state.go('lang', {lang: 'en'});
});
};
});
Controller Call to service:
After passing in the service as a dependency into the controller.
Getlanguage.getContent().then(function(res) {
$scope.content = res.data;
});
Hope this helps.

Categories