How to access rootscope in component view - html

I have angular controller dashboard and set the root scope value in dashboard and access that root scope value in component inside the dashboard template using scope..but i don't know whether this is correct or not..and am not able to get that value
function DashBoardController($http, $window, $rootScope, apiurl, $scope, $location,$interval) {
var ctrl = this;
ctrl.$onInit = function () {
getUser();
};
function getUser(){
$http({
method: 'GET',
url: apiurl + '/getUser',
}).success(function (data, status) {
if (data.status == true) {
$rootScope.user = data.result;
$rootScope.test = "TEST";
}
});
}
function Controller1($rootScope,$scope, $timeout,$http, apiurl,$interval) {
var ctrl = this;
$scope.value = $rootScope.test;
alert($scope.value);
$scope.value1 = $rootScope.user;
console.log($scope.value1);
}
app.module('app').component('component1', {
templateUrl: '../resources/views/component/component1.html',
controller: Controller1
});
})(window.angular);
am getting undefined

From template you can access rootscope variables via $root.varName

Related

how to define angular methods

I'm a regular consumer of advice from Stackoverflow. It's an invaluable tool - thanks for all the help!
But this is my first question: I'm very new to Angular but I've been doing server side stuff for donkeys years.
I've got a method on a controller, which calls a server REST service. My problem is that the method is called whenever the controller is instantiated. I know there's got to be another way of declaring the function, but I've got no idea of what to search for.
Here's my html:
<html lang="en" data-ng-app="mLS" ng-controller="mLSController">
<head>....</head>
...
<li><a ng-if="userName" ng-click="Logout()">logout</a></li>
and my module (the module def is elsewhere, but it seems ok)
var app = angular.module('mLS');
app.controller('mLSController', function ($scope, $http, $window, $location) {
$http({
url: '/api/UI/GetUsername',
method: 'GET'
}).success(function (data, status, headers, config) {
$scope.userName = data;
$scope.desiredPath = $location.path();
if (!$scope.userName && $scope.desiredPath != '/Account/Login')
$window.location.href = '/Account/Login';
});
});
function Logout($http) {
$http({ url: '/api/UI/Logout', method: 'GET' });
}
//app.
// controller('mLSController', function ($scope, $http) {
// $scope.Logout = function () {
// $http({ url: 'api/UI/Logout', method: 'GET' });
// };
// });
//app.
// controller('mLSController', ['$scope', '$http', 'Logout', function ($scope, $http, Logout) {
// $scope.callLogout = function () {
// Logout();
// };
// }]).
// factory('Logout', ['$http', function (protocol) {
// protocol({ url: 'api/UI/Logout', method: 'GET' }).success(function() {
// $scope.Logout = true; });
// }]);
So my problem is that the current code:
function Logout($http) {
$http({ url: '/api/UI/Logout', method: 'GET' });
}
just isn't called at all, and if I put it on the controller, Logout() is called when the controller is instantiated. Which isn't ideal.
Please help!
If you want the Logout function to be exposed to DOM (via Angular), you need to put it on $scope. There is no other option to call it using angular directives (ng-click).
Else, if you want it to be called before your app/controller are instantiated, use native javascript's onclick() event.
Warning: if you use onclick, you cannot set $scope variables.
So, thanks to Bharat, I've got it working!
This is the solution:
var app = angular.module('mLS');
app.controller('mLSController',
// function added to the controller
function ($scope, $http, $window, $location) {
$scope.Logout = function () {
$http({ url: 'api/UI/Logout', method: 'GET' });
return ;
};
$http({ url: '/api/UI/GetUsername', method: 'GET' }).success(function (data, status, headers, config) {
$scope.userName = data;
$scope.desiredPath = $location.path();
if (!$scope.userName && $scope.desiredPath != '/Account/Login')
$window.location.href = '/Account/Login';
});
});
For completeness, I could wrap the GetUsername call in a function, but the question is answered.
I can't upvote your answer, Bharat, because I haven't asked enough questions yet, but thanks so much!

How to map URL to node.js route

I am using ui-router with Angular and Node.js as my UI server for API calls to another server. Right now, my browser URL (dynamic based on dropdown selections) does not map to the server.
For example, the browser URL is "/home?color=Red&&size=Large" when I send the user inputs to Node. When I copy and paste that URL in another browser window, I want the color and size dropdowns to already be selected as Red and Large, and results from API call based on the selections displayed. How can I accomplish this?
My AngularJS controller code:
$scope.getResults = function() {
$location.search('color', $scope.myColor);
$location.search('size', $scope.mySize);
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};
AngularJS service for the above function:
app.factory('server', ['$http', function($http){
return {
getResults : function(color, size) {
var req = {};
req.color = color;
req.size = size;
return $http({
method: 'GET',
url: 'results',
params : req
});
}
}
}]);
ui-router in Angular:
$stateProvider.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
reloadOnSearch: false
})
In Node.js, I have my route like this:
app.get("/results", function (req, res) {
var api = 'some api call/' + req.query.color + '/' + req.query.size;
request(api, function (error, response, api) {
if (!error && response.statusCode == 200) {
res.json({
Response: api
});
}
});
});
In your code you wrote query parameters but you need to read them, try this:
$scope.getResults = function() {
$scope.myColor = $location.search().color;
$scope.mySize = $location.search().size;
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};

AngularJS : Factory JSON Array with HTTP GET

I'm developing my first AngularJS app using the Google Docs API to pass it JSON data.
This is an example of the factory I'm using:
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true});
},
updates:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/2/public/values?alt=json', {cache: true});
},
docs:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/3/public/values?alt=json', {cache: true});
}
}]);
I wanted to clean up a bit the code and decided to use services instead of making the calls in the controller itself. It works normally, but it's a pain in the ass the fact that I still need to write long $scopes because of the structure of the Google API. This is how I get the values in the controller:
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().success(function (data) {
$scope.totalNews = data.feed.entry.length;
});
}]);
Is there a way that I can set the factory service to pass me the data just using:
$scope.totalNews = Data.news()
Or at least removing the 'feed.entry'?
Data.news().success(function (data) {
$scope.totalNews = data.length;
});
Thank you very much!
example of service - resolve the success with the data you want
app.service('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
this.news =function(){
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values? alt=json', {cache: true})
.then(function(data){
return data.feed.entry.length;
});
}
}]);
the controller - since you already resolved the data in service hence..
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().then(function (data) {
$scope.totalNews = data;
});
}]);
working example
var app = angular.module('app', ['ionic'])
.service('Data', ['$http',
function($http) {
var googleDocs = 'https://spreadsheets.google.com/feeds/list/1aC1lUSxKatfxMKEy1erKDSAKgijSWOh77FDvKWhpwfg/1/public/values?alt=json';
this.news = function() {
return $http.get(googleDocs, {
cache: true
}).then(function(res) {
return res.data.feed.entry;
});
}
}
])
.controller('homeCt', ['$scope', 'Data',
function($scope, Data) {
Data.news().then(function(data) {
console.log(data);
})
}
]);
I'll give you a way of doing it, a way that I don't recommend at all (a service should not handle the scope), but for me it is the only way you have if you don't want to destroy the "async" of your ajax call :
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:news,
updates: updates,
[...]
}
function news(scopeValue) {
$http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true}).success(function(data){
scopeValue = data;
});
}]);
and then, call it that way in your controller :
Data.news($scope.totalNews);

How to load more than one json file in angular

I am wondering how to load multiple .json files in to template.
In my example I have submissions from users and I do not want to store everything in one json file if possible.
How to grab some data from multiple json files?
here is my plunk example
I want to load users.json as well
var app = angular.module('myApp', []);
app.directive('contentItem', function ($compile,$parse) {
templates = {
image: 'image.html',
event: 'event.html',
article: 'article.html',
ad: 'ad.html',
discount: 'discount.html',
video: 'video.html'
}
var linker = function(scope, element, attrs) {
scope.setUrl = function(){
return templates[scope.content.content_type];
}
}
return {
restrict: "E",
replace: true,
link: linker,
scope: {
content: '='
},
templateUrl: 'main.html'
};
});
function ContentCtrl($scope, $http) {
"use strict";
$scope.url = 'content.json';
$scope.content = [];
$scope.fetchContent = function() {
$http.get($scope.url).then(function(result){
$scope.content = result.data;
});
}
$scope.fetchContent();
}
Help appreciated
You can request for JSON either from the controller like:
app.controller('myController', function($scope, $http){
$scope.users = [];
$scope.getUsers = function() {
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).
success(function(data, status) {
$scope.users = data;
}).
error(function(data, status) {
console.log(data || "Request failed");
});
};
and the other approach (better one) would be to make use of angular factory to fetch the JSON file.
myApp.factory('getUsersFactory',['$http',function($http){
return {
getUsers: function(callback){
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).success(callback);
}
}
}]);
where now you can include this factory as a dependency and get the user data and assign that in the callback function.

Using return $q.when in Hot Towel Angular datacontext

I've created a web application using the Hot Towel Angular template, and I want to add a service function to the 'datacontext'.
Code is:
(function () {
'use strict';
var serviceId = 'datacontext';
angular.module('app').factory(serviceId, ['common', '$http', datacontext]);
function datacontext(common, $http) {
var $q = common.$q;
var service = {
getFunctions: getFunctions
};
return service;
function getFunctions() {
var f = [];
$http({
method: 'GET',
url: 'https://api.github.com/users/google/repos',
contentType: 'application/json; charset=utf-8'
})
.success(function (data, status, headers, config) {
f = data;
console.log('f=*' + f + '*');
})
.error(function (data, status, headers, config) {
alert('error!');
});
return $q.when(f);
}
}
})();
I see that the console shows some objects:
f=*[object Object],[object Object],[object O...
But when using this in my functionController.js file :
function getFunctions() {
return datacontext.getFunctions().then(function (data) {
console.log('data=*' + data + '*');
return vm.functions = data;
});
}
The value for data is set to undefined.
I'm missing something, please help identify the error.
Solution:
The getFunctions function in the datacontext should return the $http promise object, like this:
function getFunctions() {
return $http.get('https://api.github.com/users/google/repos')
.error(function (data, status, headers, config) {
alert('error ! : ' + status);
});
}
And in the controller, you can use the returned json object as follows:
function getRepos() {
return datacontext.getRepos().then(function (httpResult) {
vm.repos = httpResult.data;
});
}