Using Restangular in the App using the factory - angularjs

I have created here a working demoapp in which I have used the restangular
It is working perfectly fine but when I tired to implement the demoapp with the factory the data doesnt seem to come and I cant check out the possible bug in this
/* the file containing my json object*/
[
{"id":1,
"subject":"#aashima"
},
{"id":2,
"subject":"#aansh"
},
{"id":3,
"subject":"#artle"
},
{"id":4,
"subject":"#harish"
}
]
<!doctype html >
<html ng-app="app">
<head>
<meta charset="UTF-8">
<title>Restangular</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/restangular/1.5.1/restangular.min.js"></script>
</head>
<body>
<div ng-controller="IndexCtrl as omega" ng-cloak>
<ul>
<li ng-repeat="result in omega.people">
<span ng-bind="result.subject"></span>
</li>
</ul>
<span ng-bind="omega.harish"></span>
</div>
<script>
var app = angular.module('app', ['restangular'])
app.config(function(RestangularProvider) {
RestangularProvider.setBaseUrl("\js");
app.controller('IndexCtrl', function( testFactory) {
var self=this;
testFactory.getFriendList.then(function (homeFriends) {
self.people=homeFriends;
console.log(self.people);
});
});
app.factory('testFactory', ['Restangular', function (Restangular) {
return {
getFriendList: Restangular.all('emp.json').getList()
}
}]);
</script>
</body>
</html>

<!doctype html >
<html ng-app="app">
<head>
<meta charset="UTF-8">
<title>Restangular</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/restangular/1.5.1/restangular.min.js"></script>
</head>
<body>
<div ng-controller="IndexCtrl as omega" ng-cloak>
<ul>
<li ng-repeat="result in omega.people">
<span ng-bind="result.subject"></span>
</li>
</ul>
<span ng-bind="omega.harish"></span>
</div>
<script>
var app = angular.module('app', ['restangular'])
app.config(function(RestangularProvider) {
RestangularProvider.setBaseUrl("\js");
});
app.controller('IndexCtrl', function( Restangular, testFactory) {
var self=this;
Restangular.all('evm.json').getList().then(function(result) {
self.people = result;
});
testFactory.getFriendList.then(function (homeFriends) {
console.log(self.people);
self.people=homeFriends;
});
});
app.factory('testFactory', ['Restangular', function (Restangular) {
return {
getFriendList: Restangular.all('emp.json').getList()
}
}]);
</script>
Their is some syntax issue and I have corrected and now your App will run

Related

How do I call $http.get in AngularJS

Attempting to learn angularjs because I need to modify some stuff at work and that is what they are using and I can't upgrade to Angular2+ at the moment. I have the following code where I'm trying to use the $http.get method but getting $http not defined error in the console.
// js code
var app = angular.module('app', []);
app.controller('HelloWorldCtrl', function($scope){
var onUserComplete = function(response){
$scope.user = response.data;
};
$http.get("https://api.github.com/users/robconery")
.then(onUserComplete);
$scope.message = "Hello, AngularJS";
});
// HTML
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#*" data-semver="4.0.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="HelloWorldCtrl">
<h1>{{message}}</h1>
<div>
Name: {{user.name}}
</div>
<div>
Location: {{user.location}}
</div>
</body>
</html>
You need to pass $http as a dependency to your controller,
app.controller('HelloWorldCtrl', function($scope,$http){
});
DEMO
var app = angular.module('app', []);
app.controller('HelloWorldCtrl', function($scope,$http){
var onUserComplete = function(response){
$scope.user = response.data;
};
$http.get("https://api.github.com/users/robconery")
.then(onUserComplete);
$scope.message = "Hello, AngularJS";
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#*" data-semver="4.0.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="HelloWorldCtrl">
<h1>{{message}}</h1>
<div>
Name: {{user.name}}
</div>
<div>
Location: {{user.location}}
</div>
</body>
</html>

AngularJS not returning data from $http rest request

Any idea what I am doing wrong here?
It must be something simple but I have been trying a bunch of different combinations for hours.
Thanks in advance.
https://plnkr.co/edit/3NkmhLVLTZe3aMoiK9Ff?p=preview
app.js
var app = angular.module('fishHouseMonitorApp', []);
app.controller('fishHouseMonitorController', function($scope, $http) {
$http.get("http://www.eastcentralmdaa.org/fishhousemonitor/api/v1/sensormeasurements")
.then(function(response) {
$scope.sensormeasurements = response.data;
// do some error checking to ensure there is an element 0?
$scope.selectedElement = $scope.sensormeasurements[0];
});
});
index.html
<!DOCTYPE html>
<html ng-app="fishHouseMonitorApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
</head>
<body>
<div class="container" ng-controller="fishHouseMonitorController">
<div class="row">
<ul class="list-group">
<li class="list-group-item" ng-repeat="sensormeasurement in sensormeasurements" ng-click="selectContact($index)">
<span>{{ sensormeasurement.sensorMeasurementDateTime }}</span>
</li>
</ul>
</div>
</div>
</body>
</html>
This works:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
{{ myData }}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("https://jsonplaceholder.typicode.com/users").then(function(response) {
$scope.myData = response.data;
});
});
</script>
</body>
</html>
This does not:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
{{ myData }}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.eastcentralmdaa.org/fishhousemonitor/api/v1/sensormeasurements").then(function(response) {
$scope.myData = response.data;
});
});
</script>
</body>
</html>
even though https://jsonlint.com/ validates http://www.eastcentralmdaa.org/fishhousemonitor/api/v1/sensormeasurements as valid JSON
You cannot access an HTTP destination while running your application on HTTPS. Change your protocol to HTTPS and you will be fine:
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("https://jsonplaceholder.typicode.com/users").then(function(response) {
$scope.myData = response.data;
});
});
</script>
I did not fully understand the problem.I hope this helps
app.js
var app = angular.module('fishHouseMonitorApp', []);
app.controller('fishHouseMonitorController', function($scope, $http) {
$http.get("http://www.eastcentralmdaa.org/fishhousemonitor
/api/v1/sensormeasurements")
.then(function(response) {
$scope.sensormeasurements = response.data[0];
// do some error checking to ensure there is an element 0?
});
});
index.html
<ul class="list-group">
<li class="list-group-item" ng-model="sensormeasurements" ng-click="selectContact($index)">
<span>{{ sensormeasurement.sensorMeasurementDateTime }}</span>
</li>
</ul>

How do you set up a relationship between properties of two angular controllers?

Say I've got AdamController as adam and AnujController as anuj. I want anuj.anujProp to have a j appended to it every time adam.adamProp changes.
How could this be done? What is the best way?
Here are 4 possible ways that I came up with. I ranked them in the order that I personally feel is best.
Events - http://plnkr.co/edit/4AD8e47DaOSuutrphIkN?p=preview
Method on a Factory - http://plnkr.co/edit/Vixab8LjDtow5YYfnlMV?p=preview
Factory + $watch - http://plnkr.co/edit/1zVZ9EDarCGPOMZvrJMd?p=preview
$scope inheritance - http://plnkr.co/edit/3b7tzPI5Y4CcwWYXUk25?p=preview
The $scope inheritance approach just feels "messy". I like the event driven approach over the factory approaches because I feel like there's a sort of overhead associated with the factories, and if it's only going to be used for this one purpose, the overhead isn't worth it. Plus, this just seems to be exactly what events are for. I put (2) ahead of (3) because the $watch hurts performance.
Events
angular
.module('app', [])
.controller('AdamController', AdamController)
.controller('AnujController', AnujController)
;
function AdamController($rootScope) {
var vm = this;
vm.prop = 'adam';
vm.update = function() {
$rootScope.$broadcast('propChange');
};
}
function AnujController($scope) {
var vm = this;
vm.prop = '';
$scope.$on('propChange', function(event) {
event.currentScope.anuj.prop += 'x';
});
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app='app'>
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller='AdamController as adam'>
<input ng-model='adam.prop' ng-change='adam.update()'>
</div>
<div ng-controller='AnujController as anuj'>
<p>{{ anuj.prop }}</p>
</div>
</body>
</html>
Method on a Factory
angular
.module('app', [])
.factory('Factory', Factory)
.controller('AdamController', AdamController)
.controller('AnujController', AnujController)
;
function Factory() {
return {
anujProp: 'anuj',
update: function() {
this.anujProp += 'j';
}
};
}
function AdamController(Factory) {
var vm = this;
vm.factory = Factory;
}
function AnujController(Factory) {
var vm = this;
vm.factory = Factory;
}
<!DOCTYPE html>
<html ng-app='app'>
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller='AdamController as adam'>
<input ng-model='initial' ng-change='adam.factory.update()'>
</div>
<div ng-controller='AnujController as anuj'>
<p>{{ anuj.factory.anujProp }}</p>
</div>
</body>
</html>
Factory + $watch
angular
.module('app', [])
.factory('Factory', Factory)
.controller('AdamController', AdamController)
.controller('AnujController', AnujController)
;
function Factory() {
return {
shared: 'shared',
related: 'related'
};
}
function AdamController(Factory) {
var vm = this;
vm.factory = Factory;
}
function AnujController(Factory, $scope) {
var vm = this;
vm.factory = Factory;
$scope.$watch('anuj.factory.related', function(newValue, oldValue, scope) {
scope.anuj.factory.related = newValue.toUpperCase();
});
}
<!DOCTYPE html>
<html ng-app='app'>
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller='AdamController as adam'>
<input ng-model='adam.factory.shared'>
<input ng-model='adam.factory.related'>
</div>
<div ng-controller='AnujController as anuj'>
<p>{{ anuj.factory.shared }}</p>
<p>{{ anuj.factory.related }}</p>
</div>
</body>
</html>
$scope inheritance
angular
.module('app', [])
.controller('AdamController', AdamController)
.controller('AnujController', AnujController)
;
function AdamController($scope) {
var vm = this;
vm.adamProp = 'adam';
vm.update = function() {
var anuj = $scope.$parent.$$childTail.anuj;
anuj.anujProp += 'j';
};
}
function AnujController() {
var vm = this;
vm.anujProp = 'anuj';
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="AdamController as adam">
<input ng-model="adam.adamProp" ng-change="adam.update()" />
</div>
<div ng-controller="AnujController as anuj">
<p>{{ anuj.anujProp }}</p>
</div>
</body>
</html>

Which json type can be used with the restangular for the get request

I have created a simple demoapp and it seems to work perfectly file.
The demoapp uses restangular for the get request.
/* the emp.json file from where the data is coming*/
[
{"id":1,
"subject":"#aashima"
},
{"id":2,
"subject":"#aansh"
},
{"id":3,
"subject":"#artle"
},
{"id":4,
"subject":"#harish"
}
]
<!doctype html >
<html ng-app="app">
<head>
<meta charset="UTF-8">
<title>Restangular</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/restangular/1.5.1/restangular.min.js"></script>
</head>
<body>
<div ng-controller="IndexCtrl as omega" ng-cloak>
<ul>
<li ng-repeat="result in omega.people">
<span ng-bind="result.subject"></span>
</li>
</ul>
<span ng-bind="omega.hero"></span>
</div>
<script>
var app = angular.module('app', ['restangular'])
.config(function(RestangularProvider) {
RestangularProvider.setBaseUrl("js");
});
app.controller('IndexCtrl', function( Restangular) {
var self=this;
Restangular.all('emp.json').getList().then(function(result) {
self.people = result;
});
});
</script>
</body>
</html>
The app works perfectly but the problem in here is that the json response from my backend will be something like this
{"user":[
{"id":1,
"subject":"#aashima"
},
{"id":2,
"subject":"#aansh"
},
{"id":3,
"subject":"#artle"
}
]
}`
I tired to integrate the code with this json response, does Restangular supports this json and if it does do I need a different approach !!!

sharing a var between views/controllers

I know this question has been asked 100s of times but i have yet to succeed in implementing this after reading countless of threads... shame on me.
I know this is a lot of code (sorry). But I just can't find what I'm doing wrong,
So to the problem I want to add something to the list in pat1 then click over to pat2 and see the same list.
Routing;
var routeApp = angular.module('routeApp', ['ngRoute', 'rootMod']);
routeApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/pat1', {
templateUrl: 'partials/pat1.html',
controller: 'pageOneCont'
}).
when('/pat2', {
templateUrl: 'partials/pat2.html',
controller: 'pageTwoCont'
}).
otherwise({
redirectTo: '/pat1'
});
}]);
Controllers & Service:
var rootMod = angular.module('rootMod', []);
rootMod.controller('pageOneCont', [ 'serv', '$scope', function (serv, $scope) {
'use strict';
// Your controller implementation goes here ...
$scope.handleClick = function ($scope, serv){
var updateFoo = function(){
$scope.foo = serv.foo;
};
aService.registerObserverCallback(updateFoo);
//service now in control of updating foo
};
}]);
rootMod.controller('pageTwoCont', [ 'serv', '$scope', function (serv, $scope) {
'use strict';
// Your controller implementation goes here ...
$scope.handleClick = function ($scope, serv){
var updateFoo = function(){
$scope.foo = serv.foo;
};
aService.registerObserverCallback(updateFoo);
//service now in control of updating foo
};
}]);
/* Service */
rootMod.factory('serv', [ function () {
var observerCallbacks = [];
//register an observer
this.registerObserverCallback = function(callback){
observerCallbacks.push(callback);
};
//call this when you know 'foo' has been changed
var notifyObservers = function(){
angular.forEach(observerCallbacks, function(callback){
callback();
});
};
}]);
INDEX.html
<!doctype html>
<html lang="en" ng-app="routeApp">
<head>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body>
<li> ONE </li>
<li> TWO </li>
</body>
<!-- SinglePage -->
<div ng-view></div>
</html>
PAT1.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular Test</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
<script src="js/controllers.js"></script>
</head>
<div ><!--ng-app="myModule" ng-controller="ContactController">-->
<h1> ONE </h1>
<button ng-click="handleClick"> BROADCAST </button>
<div ng-repeat="item in foo">{{ item }}</div>
</div>
</html>
PAT2.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular Test</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
<script src="js/controllers.js"></script>
</head>
<div> <!--ng-app="myModule" ng-controller="ContactController">-->
<h1> TWO </h1>
<div ng-repeat="item in foo">{{ item }}</div>
</div>
</html>
JS
Your service is injected as serv in your controllers but you call aService. Use serv instead.
You should use rootMod.service() instead of rootMod.factory() since you are using this and not returning anything in your service function (see this for the difference between factories and services).
There is no serv.foo property. You have to add this.foo = /** something **/; to your service function.
So this should work:
var rootMod = angular.module('rootMod', []);
rootMod.controller('pageOneCont', [ 'serv', '$scope', function (serv, $scope) {
'use strict';
// Your controller implementation goes here ...
$scope.handleClick = function ($scope, serv){
var updateFoo = function(){
$scope.foo = serv.foo;
};
serv.registerObserverCallback(updateFoo);
// service now in control of updating foo
};
}]);
rootMod.controller('pageTwoCont', [ 'serv', '$scope', function (serv, $scope) {
'use strict';
// Your controller implementation goes here ...
$scope.handleClick = function ($scope, serv){
var updateFoo = function(){
$scope.foo = serv.foo;
};
serv.registerObserverCallback(updateFoo);
// service now in control of updating foo
};
}]);
/* Service */
rootMod.service('serv', [ function () {
var observerCallbacks = [];
// call this when you know 'foo' has been changed
var notifyObservers = function(){
angular.forEach(observerCallbacks, function(callback){
callback();
});
};
// initialize foo here
this.foo = '';
// register an observer
this.registerObserverCallback = function(callback){
observerCallbacks.push(callback);
};
}]);
HTML
You put the ng-view container outside of the body. It has to be inside. Also the path to a view starts with #/ so you have to change your links.
<!doctype html>
<html lang="en" ng-app="routeApp">
<head>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body>
<li> ONE </li>
<li> TWO </li>
<!-- SinglePage -->
<div ng-view></div>
</body>
</html>
Each view only needs the content that should be placed inside the ng-view container. So you mustn't make a complete HTML document.
pat1.html
<h1> ONE </h1>
<button ng-click="handleClick"> BROADCAST </button>
<div ng-repeat="item in foo">{{ item }}</div>
pat2.html
<h1> TWO </h1>
<div ng-repeat="item in foo">{{ item }}</div>

Resources