data to read my json file in IONIC - angularjs

This world is sad to cry , am blocked for two hours with a problem that i couldnt define ,i can't retrieve data from my json file ,everything in my code seems correct.
This is my factory:
'use strict';
angular.module('starter.services')
.factory('userService',function ($http) {
return{
getUsers:function(){
return $http.get("http://localhost:26309/api/User/getAll/").then(function (response) {
return response.data;
});
}
}
});
and this controller :
'use strict';
angular.module('starter.controllers', ['starter.services'])
.controller('UsersCtrl', function($scope,userService) {
$scope.Users = [];
userService.getUsers().then(function (data) { $scope.Users= data.data; }); });
});
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic/js/angular/angular-resource.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/UserControllerIonic.js"></script>
<script src="js/UsersServiceIonic.js"></script>
</head>
<body ng-app="starter" ng-controller="UsersCtrl">
<ion-view>
<div class = "list" >
<a class = "item" ng-repeat = "user in Users">
<h2>{{user.nom}}</h2>
</a>
</div>
</ion-view>
</body>
</html>
Thank you in advance
SOLUTION
i solved the problem by :
1- adding in the config.xml the permission <allow-navigation href="http://*/*"/>
2-installing cordova-plugin-whitelist ionic plugin add cordova-plugin-whitelist
3-add control-allow-origin extention to chrome :https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related?hl=en-US
and finally : specifying the type of data returned by the back-end controller by adding this code to my Global.asax in Application_start method :config.Formatters.JsonFormatter.SerializerSettings.Formatting =
Newtonsoft.Json.Formatting.Indented;
config.Formatters.Remove(config.Formatters.XmlFormatter);
hope this helps someone

You don't want to resolve your $http call inside factory.
JS:
angular.module('app',[])
.controller('MainCtrl', function($scope, MyService){
var url = "http://jsonplaceholder.typicode.com/users";
MyService.getData(url).then(function(res){
console.log(res.data);
$scope.data = res.data;
});
})
.service('MyService', function($http){
return {
getData: function(url){
return $http.get(url);
}
}
})
HTML:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in data">{{item.name}}</li>
</ul>
</body>
</html>

The issue is that you are resolving the promise in service with the value response.data, and again expecting the resolved value to have data property. Change your service code as below:
'use strict';
angular
.module('starter.services')
.factory('userService',function ($http) {
return {
getUsers: function(){
return $http.get("http://localhost:26309/api/User/getAll/").then(function (response) {
return response;
});
}
}
});
Or simply return the promise as below:
'use strict';
angular
.module('starter.services')
.factory('userService',function ($http) {
return {
getUsers: function(){
return $http.get("http://localhost:26309/api/User/getAll/");
}
}
});

Related

Taking screenshot via button in ionic/cordova using screenshot plugin

I want my ionic project to take a screenshot and store it in camera roll.
currently the button is not able to take any screenshot. I am testing the app on an android device.
I am using this plugin: https://github.com/gitawego/cordova-screenshot
index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-view>
<ion-content>
<button class="button" ng-click="$cordovaScreenshot.capture()">screenshot</button>
</ion-content>
</ion-view>
</body>
</html>
app.js
angular.module('starter', ['ionic','ngCordova'])
.service('$cordovaScreenshot', ['$q', function($q) {
return {
capture: function(filename, extension, quality) {
filename = filename || 'pic';
extension = extension || 'jpg';
quality = quality || '100';
var defer = $q.defer();
navigator.screenshot.save(function(error, res) {
if (error) {
console.error(error);
defer.reject(error);
} else {
console.log('screenshot saved in: ', res.filePath);
defer.resolve(res.filePath);
}
}, extension, quality, filename);
return defer.promise;
}
};
}]);
As a follow-up on my first comment. I think you need a controller between the view (HTML) and your Angular service. A HTML view can't directly communicate with a service, so we need a intermediate controller.
Something along the lines of:
angular.module('starter', ['ionic','ngCordova'])
.controller('myController', ['$cordovaScreenshot', function($cordovaScreenshot) {
$scope.captureScreenshot = function() {
$cordovaScreenshot.capture('filename', 'png', 100).then(function(result) {
// do something with result
}, function(error) {
// do something with error
});
};
}]);
As you can see, we're using dependency injection to inject the $cordovaScreenshot service.
And your view will trigger the captureScreenshot method:
<ion-content ng-controller="myController">
<button class="button" ng-click="captureScreenshot()">screenshot</button>
</ion-content>
Notice the ng-controller and a change in the ng-click method.
The problem was rectified.
The code can be found at
https://github.com/manik1596/coredovaScreenshotShare

Ionic controllers and services

I'm pretty new with Ionic and AngularJS. I tried to create an app but it seems that the content of app.js is wrong .
This is my code look like :
app.js
angular.module('starter', ['ionic', 'starter.controllers'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('app', {
url: "/ListeUsers",
views: {
templateUrl: "templates/ListeUsers.html",
controller: 'UsersCtrl'
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/ListeUsers');
});
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic/js/angular/angular-resource.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/UserControllerIonic.js"></script>
<script src="js/UsersServiceIonic.js"></script>
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
</body>
</html>
userControllerIonic.js
angular.module('starter.controllers', ['starter.services'])
.controller('UsersCtrl', function($scope,userService) {
$scope.Users=userService.getUsers();
});
UsersServiceIonic.js
angular.module('starter.services', ['ngResource'])
.factory('userService',function () {
var Users =[];
return{
getUsers:function(){
return $http.get("http://localhost:26309/api/User/getAll/").then(function (response) {
users=response;
return users;
});
},
getUser : function(UserName) {
return $http.get("http://localhost:26309/api/User/getUserByNom/" + UserName).then(function (serviceResp) {
return serviceResp.data;
});
}
}
})
ListeUsers.html
<ion-list>
<ion-item ng-repeat="user in Users"
>{{user.nom}}</ion-item>
</ion-list>
i can't find the problem
There are 2 issues you need to fix here for your app to work:
You need to correct he default fallback url from /app/ListeUsers to /ListeUsers because /app/ListeUsers path will be valid if the state was a child-state of app. See more details here: https://github.com/angular-ui/ui-router/wiki/Nested-States-and-Nested-Views
Your service methods are returning promises. You cannot assign a promise to a $scope variable and expect the app to be working. Change your controller code to use the parameter from the .then method callback of the returned promise as below:
angular
.module('starter.controllers', ['starter.services'])
.controller('UsersCtrl', function($scope,userService) {
userService.getUsers()
.then(function (response) {
$scope.Users= response;
});
});

$http.get call app.get in Express

Code in server.js
var strava = require('node-strava-v3')
var express = require('express');
var app = express();
app.get('/', function(req, res){
strava.streams.activity({'id': 497191235, 'types':'distance'}, function(err, payload){
if(!err){
res.send(payload);
}
else{
res.send(err);
}
})
});
I would like to setup a view file (static HTML with a dynamic view) which gets its data via a controller file, which in turn retrieves it from the model (server.js) through app.get() call. I believe I would need to utilise $http.get() from the controller to access app.get()? The tutorials I read have provided a specifc path as the argument for $http.get(), but I don't think it applies to my situation.
Please advise - thank you.
[Edit] controller.js and index.html files at present:
//controller.js
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http',
function($scope, $http){
var refresh = function(){
$http.get('/').success(function(response){
$scope.contactlist = response;
});
};
refresh();
}]);
//index.html
<!DOCTYPE>
<html ng-app="myApp">
<head>
<title>Contact List App</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<script src="controller.js"></script>
</head>
<body>
<div class="container" ng-controller="AppCtrl">
<p>{{contactlist}}</p>
</div>
</body>
</html>

How to update controller variable with 'ng-model' AngularJS?

I am trying to get user input through a text box using ng-model, and append to a base URL for a http.get call as follow;
index.html:
<html ng-app='vidRoute'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Search Video</title>
<link rel="stylesheet" href="app/css/custom/main.css">
<link rel="stylesheet" href="app/css/custom/responsive.css">
</head>
<body>
<div id='mainwrapper'>
<div id='header' ng-controller="searchController">
<input type="text" id="searchTxt" ng-model="append">
Search Video
</div>
<div id="poster">
<div ng-view></div>
</div>
</div>
<script type="text/javascript" src="app/javascript/vendor/jquery-2.1.1.js"></script>
<script type="text/javascript" src="app/javascript/vendor/angular.js"></script>
<script type="text/javascript" src="app/javascript/vendor/angular-route.js"></script>
<script type="text/javascript" src="app/javascript/vendor/angular-resource.js"></script>
<script type="text/javascript" src="app/javascript/vendor/angular-mocks.js"></script>
<script type="text/javascript" src="app/javascript/custom/searchcontroller.js"></script>
<script type="text/javascript" src="app/javascript/custom/vidRoute.js"></script>
</body>
</html>
searchcontroller.js
'use strict';
var vidcontrol = angular.module("vidcontrol", []);
vidcontrol.controller("vidcontroller", ['$scope', '$http', function($scope, $http) {
$http.get('http://api.themoviedb.org/3/tv/airing_today?api_key=d5e87524383e2872a9555990b268dc5b').success(function(response) {
$scope.results = response.results;
});
}]);
vidcontrol.controller('searchController', ['$scope', '$http',
function ($scope, $http) {
var url = "http://api.themoviedb.org/3/search/movie?api_key=d5e87524383e2872a9555990b268dc5b&query=";
// var searchTxt = $('#searchTxt').val();// this works fine when used
var searchUrl = url + append; //$scope.append also logs 'undefined' on the console
$http.get(searchUrl).success(function (response) {
$scope.searchResults = response.results;
});
}]);
but I'm not getting any response. when I log searchUrl on console, I could see that append was not updated according to value from text box. I'm quite new to Angular and I can't figure out what I'm doing wrong. What should I do to fix this?
Now, I see the issue. When controller loaded, it executes controller code. That mean REST query runs before view is built. That is reason you see undefined problem. Solution is to define a method in controller which will be invoked when you click "Search Video".
Update view
Search Video //Look at ng-click
Update Controller:
vidcontrol.controller('searchController', ['$scope', '$http',function($scope, $http) {
var url = "http://api.themoviedb.org/3/search/movie?api_key=d5e87524383e2872a9555990b268dc5b&query=";
$scope.search = function(){ // Look at here, Defined a method to invoke on "Search Video" link click
var searchUrl = url + $scope.append;
$http.get(searchUrl).success(function(response) {
$scope.searchResults = response.results;
});
};
} ]);

Angularjs getting data from controller scope to directive scope

I am trying to get data from resource then add it to isolate scope of directive but when i want to print it to screen i get error as undefined current_page here is the script
/**
* Created by yigit on 10.01.2014.
*/
var app = angular.module('kategori', [
'ngResource',
'apiBaseRoute'
]);
app.factory('Data', ['$resource', 'apiBaseRoute', function($resource, config){
return $resource(config.apiBasePath + 'kategori/?page=:page',{page:1},{
query:{
isArray: false,
method: 'GET'
}
});
}]);
app.controller('KategoriListCtrl',['$scope', 'Data', function($scope, Data){
$scope.allData = {data:null};
Data.query({}, function(data){
$scope.kategoriList = {data:data.cat.data};
$scope.allData.data = data.cat;
});
}]);
app.directive('paginate', function(){
return{
scope:{paginatorData: '=paginate'},
link: function(scope){
alert(scope.paginatorData.current_page);
}
}
});
<!DOCTYPE html>
<html ng-app="kategori">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<div class="col-md-6 col-md-offset-3" ng-controller="KategoriListCtrl">
{{allData.current_page}}
<div paginate="allData"></div>
</div>
<script src="js/lib/angular.min.js"></script>
<script src="js/lib/angular-resource.js"></script>
<script src="js/kategori.js"></script>
<script src="js/apiroute.js"></script>
</body>
</html>
I read this article nested scope
But could not solve my problem.
So, the code alerts undefined. How can i solve this?
Can you show your HTML? You'll need to pass the property like this:
<div data-paginate="paginate"></div>

Resources