save rootscope value in the project - angularjs

I have a task to store a model value in my Electron Angular project . The rootscope model is binding the file path value .
I want to save this path on my project and every time when user will open this app by default it will be present there
$rootScope.Path = user_path[0];
I want to save this $rootScope.Path and make the data persist on that location everytime.
Any way to achieve this in electron/node.js ?
EDIT:-
$rootScope.fPath = "C:\\";
/*Configure FILE path*/
const {dialog} = require('electron').remote;
$scope.getFile = function(){
var file_path = dialog.showOpenDialog({
properties: ['openDirectory']
});
console.log(file_path);
$rootScope.fPath = file_path[0] + "\\bin";
I want to make this $rootScope.fPath path persist whenever I will open my app the previous selected path must be there already. So that I don't have to make further changes.

having a code snippet helps... is this what you're looking for ??
var app = angular.module('myApp', []);
app.run(function($rootScope) {
$rootScope.fpath = 'http://someSite/someFile';
});
app.controller('myCtrl', function($scope, $rootScope) {
console.log("fpath:" + $rootScope.fpath);
$scope.getFile = function(){
var file_path = dialog.showOpenDialog({
properties: ['openDirectory']
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp">
<p>The fPath as defined globally: <mark>{{fpath}} </mark></p>
<div ng-controller="myCtrl">
<p>The fPath as when accessed in the controller: <mark>{{fpath}}</mark> </p>
</div>
</div>

Related

Updating HTML in Angular is not working

I am still learning angular and in my example projekt I have a problem on updating the view.
Got this in my header ....
<meta charset="UTF-8">
<title>{{ name }}</title>
And this in my body:
<body ng-controller="BodyController as body">
<input type="button" ng-click="changeTitle()" name="changeNameButton" value="change name"/>
This is my head controller:
myApp.controller('HeadController',
['$scope', 'ApplicationService', 'DataService', 'UserService', function ($scope, ApplicationService, DataService, UserService) {
var self = this;
$scope.name = ApplicationService.getTitle();
}]
);
And here is my body controller:
myApp.controller('BodyController', ['$scope', 'ApplicationService', function ($scope, ApplicationService) {
$scope.text = 'Hello, Angular fanatic.';
$scope.changeTitle = function () {
console.log('change the title');
ApplicationService.setTitle('test');
}
}]);
This is my application service
myApp.service('ApplicationService', ['ConfigurationService', function(ConfigurationService){
this.title = '';
this.setTitle = function (newTitle) {
console.log('new title (setter): ' + this.title);
this.title = newTitle
}
this.getTitle = function () {
if(this.title==''){
this.title = ConfigurationService.title + ' | ' + ConfigurationService.subtitle;
}
console.log('new title (getter): ' + this.title);
return this.title;
}
}]);
So far so good and sorry that I do not use codepen, etc. But it was not working in it, ...
My Problem: It is setting the title on initial load of the website, but not on pressing the button. The new name is set to ApplicationService.title, but header controller does not update it. Whats is wrong in this case? How can I update the title in the view...?
Regards
n00n
see the codepen for it: https://codepen.io/n00n/pen/bqaGKY
What you're doing is the equivalent of the following simple code:
//in the header controller
var name = service.getTitle();
// in the header template
display(name);
// later, in the body
service.setTitle('test');
// in the header template
display(name);
You see that this can't work: the variable name in the header controller has been initialized when the controller was created, and assigning a new value to the title stored in the service can't magically change the value of the name variable in the header controller. What you want is to display the title in the service:
<title>{{ getTitle() }}</title>
$scope.getTitle = function() {
return ApplicationService.getTitle();
};
That didn't work because you're calling getTitle method when title wasn't set. So that's it is referring to older title('undefined'). You can change your binding to
$scope.getTitle = ApplicationService.getTitle;
And then change HTML to
{{getTitle()}}
So title will get fetch from service and updated on the page on each digest cycle.
Other thing which I'd like to mention is, don't use(mix) $scope when you are using controllerAs, so then remove $scope from controller and bind data to below
var vm = this;
vm.getTitle = ApplicationService.getTitle;

How to make external API call to Yelp in Node.js/Express/Angular app

I am trying to make an API call to Yelp in my Node.js app. I saw from here that I should use this code in order to be able to use the Yelp API: https://arian.io/how-to-use-yelps-api-with-node/ . I used that code in my app.js file. Now in order for it to display the results on the browser I know that I have to connect the controller to the view (in my case index.html) and bind the two files with $scope. But I would also have to somehow connect the controller to app.js. The tutorial that I followed on arian.io said:
Now if you call the function request_yelp(params, callback) it will call the callback with these arguments, callback(error, response, body).
That's it, now you're ready to take full advantage Yelp's API.
but how or where do I call that function? I assume I'd do it in my controller but I have tried that but it didn't work.
To summarize my issue, if the API call is right and it is where it should be, then my next step is to link that with my controller, once those two are connected, I have to bind html with apiController.js with $scope in order to bring my data results to be displayed in the browser. I know I am missing a lot of things, but I think I have the right idea.
Any help is welcome. Thanks!
My app's tree
>.git
>bower_components
>client
>controllers
-apiControllers (My one and only controller)
>css
>views (This is empty)
app.js
index.html (This is my one and only page/ my app is a one page app)
package.json
>models
>node_modules
app.js (This is where I am trying to make the API call)
<-- ================================================== -->
//This is my app.js file
//Call packages needed
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var dotenv = require('dotenv').config();
var oauthSignature = require('oauth-signature');
var n = require('nonce')();
var request = require('request');
var qs = require('querystring');
var _ = require('lodash');
// Function for yelp call
var request_yelp = function(set_parameters, callback) {
var httpMethod = 'GET';
var url = 'http://api.yelp.com/v2/search';
var default_parameters = {
location: 'New+York',
sort: '2'
};
var required_parameters = {
oauth_consumer_key : process.env.yelp_consumer_key,
oauth_token : process.env.yelp_token,
oauth_nonce : n(),
oauth_timestamp : n().toString().substr(0,10),
oauth_signature_method : 'HMAC-SHA1',
oauth_version : '1.0'
};
var parameters = _.assign(default_parameters, set_parameters, required_parameters);
var consumerSecret = process.env.yelp_consumer_secret;
var tokenSecret = process.env.yelp_token_secret;
var signature = oauthSignature.generate(httpMethod, url, parameters, consumerSecret, tokenSecret, { encodeSignature: false});
parameters.oauth_signature = signature;
var paramURL = qs.stringify(parameters);
var apiURL = url+'?'+paramURL;
request(apiURL, function(error, response, body){
return callback(error, response, body);
});
};
app.use(express.static(__dirname+'/client'));
app.get('/', function request_yelp(params, callback){
res.send('This is the main page');
});
app.listen(3000);
console.log('Running on port 3000');
<-- ================================================== -->
<!-- This is index.html. Here I would like to display my YELP responses. I am using Bootstrap
<div class="container-fluid">
<div class="row-fluid">
<!-- <div class="container-fluid"> -->
<!-- <div class="jumbotron"> -->
<div class="row-fluid">
<!-- <div ng-controller="MainCtrl"> -->
<p><date-input name="info.name" message="info.message"></date-input></p>
<div data-ng-repeat="business in businesses">
<!-- <div class="col-lg-offset-1"> -->
<div class="col-lg-2 col-lg-offset-2 col-md-3 col-sm-2 col-xs-6 text-center">
<p>Breakfast</p>
<div class="thumbnail">
<img class="img-responsive img-circle" src="{{business.image_url}}">
<h5>{{business.name}}</h5>
<h5>{{business.rating}}</h5>
<h5>"{{business.snippet_text}}"</h5>
<h5>{{business.categories[0]}}</h5>
<p><a class="btn btn-link btn-sm" href="{{business.url}}">View details ยป</a></p>
<p><a class="btn btn-xs btn-info" id="breakfast" role="button" onClick="refreshPage()">I don't like this one!</a></p>
</div><!-- End thumbnail -->
</div><!-- End col-md-4 -->
<-- ================================================== -->
// Finally this is my apiController.js. What code do I need here to connect the API call to my view?
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope'function($scope) {
$scope.total = [];
$scope.businesses = [];
}])
First off, I'm going to make a series of observations before I attempt to answer your question.
Your app.js file seems to be doing too much. I understand that you want to make a single page app, but some structure could help. It will be nice if you let your app.js file handle the application bootstrapping logic. That is connecting to your database and firing your express server
var express = require('express'),
routes = require('./routes'),
app = express();
/*load application middleware here */
/*Connect to databse, if needed */
/* load routes */
routes(app)
/*Fire up the server */
app.listen(3000, function (){
console.log('Server listening on port 3000');
});
You need to have a controller that handles the making of any external API calls as well as saving to your database. The controller file is where you will make your API call, in a method of some sort.
module.exports = {
makeApiCall: function(req, res) {
/* return response after call */
}
}
After you set up your controller, you will need to expose the functionality on a route, like so:
var controller = require('./controller');
module.exports = function(){
app.get('routes/segment', controller.method);
/* load more routes if any */
}
Then in angular you need to create a service that makes a call to the route segment on your backend and returns the response. You'll inject the service into your controller and make the controller available on your page however is more convenient for you.
Ex. Filename.service.js
angular.module('MyModule')
.service('ServiceName', ['$http', 'anotherDependency', ServiceFunction]);
function serviceFunction ($http, anotherDependency) {
return {
$http.get('route/segment').then(function (res) {
/*return response, promises are better */
}, function (err) {
/* Return error if any */
});
}
}
FileName.controller.js
angular.module('MyModule')
.controller('MyController', ['ServiceName', ControllerFunction]);
function controllerFunction(ServiceName){
var vm = this;
ServiceName.makeCall().then(function (res){
//set result on vm to make it accessible on your view.
}).catch(function (err)) {
//report error if any
}
}
Then on your view, you can load the controller using the Controller as Syntax.

How to save selected language in local storage or cookies in angular js

I'm new in angularjs. I need to save the language selected from a select tab in html, in local storage or cookies, that when user navigates to another page, the new page opened load and use the language selected in previous page.
Like now, if change page or just refresh the current page, selected language disappear and user must select it agin.
I used bower components for angular js, and load translation from static files.
Here is my Html code:
<div >
<section class="caret">
<h4>Select language for translation:</h4>
<select class="caret" ng-change="translate()" ng-model="selectedLanguage">
<option class="caret" value="en">English</option>
<option class="caret" value="no">Norsk</option>
</select>
</section>
<div>
My app
var app = angular.module('myApp', ['ngResource']);
My controller
app.controller('myController',['$scope', 'translationService',
function ($scope, translationService){
//Run translation if selected language changes
$scope.translate = function(){
translationService.getTranslation($scope, $scope.selectedLanguage);
};
//Init
$scope.selectedLanguage = 'en';
$scope.translate();
}]);
My translation service
app.service('translationService', function($resource) {
this.getTranslation = function($scope, language) {
var languageFilePath = 'translation_' + language + '.json';
console.log(languageFilePath);
$resource(languageFilePath).get(function (data) {
$scope.translation = data;
});
};
});
Thank you.
You can simply use localStorage. As long as you just need String-Key-Value-Pairs, you'll be fine using it just like below.
Once you need to persist Objects and the like, you could use JSON.stringify and JSON.parse to serialize them.
Here's your updated code, see the comments:
app.controller('myController',['$scope', 'translationService',
function ($scope, translationService){
$scope.translate = function(){
translationService.getTranslation($scope, $scope.selectedLanguage);
//Save changes to localStorage
localStorage.setItem('selectedLanguage', $scope.selectedLanguage);
};
//Init
//Set initial value or default
$scope.selectedLanguage = localStorage.getItem('selectedLanguage') || 'en';
$scope.translate();
}]);

Reading data from firebase in angularfire

I have an app where I need to store artists and their details in database.Now I want to retrieve all the artists and render some of their details in front end.How to do that.
Secondly, if I get the artist rating in some input field by using ng-model, then how to store that value in a particular artist to update details.
The database structure is:
{
"artists": {
"Atif":{
"name":"atif",
"rating":8
},
"Himesh":{
"name":"himesh",
"rating":5
}
}
}
and this is angular.js
(function()
{
var app = angular.module("myapp", ["firebase"]);
app.controller("maincontroller", function($scope, $firebaseObject,$firebaseArray)
{
var ref = new Firebase("https://gigstart.firebaseio.com/");
var artists=ref.child("artists");
// download the data into a local object
$scope.data = $firebaseObject(ref);
// putting a console.log here won't work, see below
ref.on("value", function(snapshot)
{
console.log(snapshot.val());
}, function (errorObject)
{
console.log("The read failed: " + errorObject.code);
});
var artistsRef=new Firebase("https://gigstart.firebaseio.com//artists");
}); //end of controller
Now I want to render the name and rating of each artist in front end.Can I do something like
<div ng-repeat="artist in artists">
{{artist.name}}
{{artist.rating}}
</div>
You have a list of artists, which you want to ng-repeat over in your Angular view. You can accomplish that by:
app.controller("maincontroller", function($scope, $firebaseArray)
{
var ref = new Firebase("https://gigstart.firebaseio.com/");
var artists = ref.child("artists");
$scope.artists = new $firebaseArray(artists);
}
Please take a moment to go through the AngularFire quickstart before starting on your own project. This is covered in step 5.

How to toggle Angularjs ng-show without $rootScope

As you might have read on the Angularjs FAQ the use of $rootScope is not encouraged. Therefore, a service is more appropriate for storing data that would be shared later on between controllers.. But I couldn't make the ng-show directive work without the use of $rootScope.
Here's what i'm doing;
index.html
<div ng-controller="GlobalCtrl">
<div ng-show="showSettings"></div>
<aside ng-show="showSettings" >
<h1>Some text</h1>
<button ng-click="closeSettings()">Ok</button>
</aside>
</div>
app.js
(I bootstrap the app since I'm developing for cordova.. code truncated)
var app = angular.module('tibibt', ['tibibt.controllers', 'tibibt.filters', 'tibibt.services']);
angular.element(document).ready(function () {
angular.bootstrap(document, ['tibibt']);
});
services.js
/* Create an application module that holds all services */
var tibibtServicess = angular.module('tibibt.services', []);
/* Global service */
tibibtServicess.service('globalService', function () {
this.Data = {
showSettings: 'false'
};
this.getAll = function () {
return this.Data;
};
this.setSettings = function (val) {
this.Data.showSettings = val;
};
});
controllers.js
/* Create an application module that holds all controllers */
var tibibtControllers = angular.module('tibibt.controllers', []);
tibibtControllers.controller('GlobalCtrl', function ($scope, globalService) {
// Get initial value
$scope.showSettings = globalService.getAll().showSettings;
console.log('Settings initially set to -> ' + globalService.getAll().showSettings);
// Open settings menu
$scope.openSettings = function () {
globalService.setSettings('true');
console.log('Settings set to -> ' + globalService.getAll().showSettings);
};
// Close settings menu
$scope.closeSettings = function () {
globalService.setSettings('false');
console.log('Settings set to -> ' + globalService.getAll().showSettings);
};
});
The console shows the changes but the ng-show doesn't bind/update to this changes!
this is only an assignment thats evaluated once:
$scope.showSettings = globalService.getAll().showSettings;
so the value will never change.
there are at least to possible solutions:
assign the service to the scope: $scope.settings = globalService. Now you may access the service in your view:
ng-show="settings.getAll().showSettings"
or register a watch by yourself:
$scope.showSettings = false;
$scope.$watch(globalService.getAll().showSettings, function(newValue){
$scope.showSettings = newValue;
});
Try:
$scope.Data = globalService.getAll();
HTML:
<div ng-controller="GlobalCtrl">
<div ng-show="Data.showSettings"></div>
<aside ng-show="Data.showSettings" >
<h1>Some text</h1>
<button ng-click="closeSettings()">Ok</button>
</aside>
</div>
DEMO
Explanation:
This line $scope.showSettings = globalService.getAll().showSettings; assign data by value => the value of showSettings is copied to $scope.showSettings => they are 2 separate blocks of memory. When you change the globalService.Data.showSettings, $scope.showSettings is not updated because it's another block of memory.
Changing to $scope.Data = globalService.getAll(); assign data by reference => they point to the same block of memory.

Resources