how to pass global variable in view to controller angularjs - angularjs

I'm tring to send backend by ejs to the frontend , controller of angularjs
app.js
i pass data to view/indexcontens.
var users = [
{
name: 'john',
email: 'john#email.com'
},
{
name: 'peter',
email: 'peter#email.com'
},
{
name: 'max',
email: 'max#email.com'
}
];
app.get('/partials/indexContents.html', function(req, res) {
res.render('partials/indexContents', {users:users})
});
app.get('/partials/about.html', function(req, res) {
res.render('partials/about')
});
views/partials/indexContents
i made it global variable.
<div>
<h3>home</h3>
<p>wecome to my blog. I hope you enjoy the content!</p>
<ul>
<li ng-repeat="post in blogposts">{{post}}</li>
</ul>
</div>
<script>
users = "<%=abc=users[0].name%>";
</script>
public/js/contollers.js trying to get the global variable
var app= angular.module('blog',['ngRoute']);
app.config(function($routeProvider) {
//set up routes
$routeProvider
.when('/home',{
templateUrl:'partials/indexContents.html',
controller:'SimpleController'
})
.when('/about',{
templateUrl:'partials/about.html',
controller:'AboutController'
})
.otherwise({
redirectTo:'/'
});
});
app.controller('SimpleController', function($scope){
$scope.blogposts=[
'blog post1',
'blog post2',
window.users
];
});
app.controller('AboutController', function($scope){
$scope.name="graum";
$scope.bio="i just made it";
});
but it only display blank instead of 'john'.
Please give me a solution, thank you

Why dont you use $resource to get the name from server? I know this is not the best option and certainly not what you are looking for but this way it works for sure.
however you can try this too
<script>
(function() {users = "<% users[0].name%>";})();
</script>

Related

How to post file and data with AngularJS with MEAN stack

I went through hundreds of pages for several days without success and here is my problem.
I use the MEAN stack and at this point I have a simple form that works very well to save a "name" field to a MongoDB collection. Now, I would like, client-side, add an image upload and, on form submit, store the image on my server and finally save the "name" field and the image path to the MongoDB collection.
AngularJS side, I tried using ng-file-upload with multer server-side. I have done well to operate for the upload of the file but only that. But after hundreds of tests, I despair. Here is an extract of my original code without file upload.
Server side
sections.server.model
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var SectionSchema = new Schema({
name: {
type: String,
default: '',
trim: true,
required: true,
unique: true
},
image: {
type: String,
default: ''
}
});
mongoose.model('Section', SectionSchema);
sections.server.controller
exports.create = function (req, res) {
var section = new Section(req.body);
section.save(function (err) {
if (err) {
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
res.json(section);
}
});
};
sections.server.routes
var sections = require('../../app/controllers/sections.server.controller');
module.exports = function (app) {
app.route('/api/sections')
.post(sections.create);
};
Client side
sections.client.module
'use strict';
var sections = angular.module('sections', []);
sections.client.controller
'use strict';
angular.module('sections')
.controller('SectionsController',
['$scope', '$routeParams', '$location', 'Sections'
function ($scope, $routeParams, $location, Sections) {
$scope.create = function () {
var section = new Sections({
name: this.name
});
section.$save(function (response) {
$location.path('sections/' + response._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
}]);
sections.client.routes
angular.module('sections').config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/sections', {
controller: 'SectionsController',
templateUrl: 'sections/views/list-sections.client.view.html'
})
.when('/sections/create', {
controller: 'SectionsController',
templateUrl: 'sections/views/create-section.client.view.html'
})
.otherwise({
redirectTo: '/'
});
}]);
sections.client.service
'use strict';
angular.module('sections').factory('Sections', ['$resource', function ($resource) {
return $resource('api/sections/:sectionId', {
sectionId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}]);
create-section.client.view
<section>
<h1>New Article</h1>
<form data-ng-submit="create()" novalidate>
<div>
<label for="name">Nom du rayon</label>
<div>
<input type="text" data-ng-model="name" id="name" placeholder="Name" required>
</div>
</div>
<div>
<input type="submit">
</div>
<div data-ng-show="error"><strong data-ng-bind="error"></strong></div>
</form>
</section>
Now, from this can anyone help me to add the image upload in the form and then save the field name and the image path in MongoDB.
Note that I want to reuse the upload mecanism in other forms of my app.
I had the idea of switching a generic middleware function in the road-side server wich call multer and return the image path to my sections.create function for MongoDB storing, something like that :
module.exports = function (app) {
app.route('/api/sections')
.post(uploads.upload, sections.create);
But I've never managed to pass the file in the POST from AngularJS request.
Thank you so much for all your ideas, your help and possibly an example of code that works.

I'm looking for a way to take the hard coded "Character" data in my Angular app and load it from a separate json file

I'm looking for a way to take the hard coded "Character" data in my Angular app and load it from a separate json file.
I have a controller for the ($http) thats worked in other apps, I'm just not sure how to strip, pull and access these character names and properties from a JSON file. Any help would be appreciated.
<body>
<div class="container">
<div ng-app="polarisApp">
<h1>The Other Guys</h1>
<h3>Custom Events in Nested Controllers</h3>
<div ng-controller="Characters">
<div class="lList"> <span ng-repeat="name in names" ng-click="changeName()">{{name}}</span>
</div>
<div class="cInfo">
<div ng-controller="Character">
<label>Name:</label>{{currentName}}
<br>
<label>Job:</label>{{currentInfo.job}}
<br>
<label>Weapon:</label>{{currentInfo.weapon}}
<br> <span ng-click="deleteChar()">Delete</span>
</div>
</div>
</div>
</div>
<script src="http://code.angularjs.org/1.3.0/angular.min.js"></script>
<script src="angular.js"></script>
<script>
angular.module('polarisApp', [])
.controller('Characters', function ($scope) {
$scope.names = ['Alan', 'Terry', 'Gene', 'Sheila', 'Danson', 'Highsmith', 'Bob'];
$scope.currentName = $scope.names[0];
$scope.changeName = function () {
$scope.currentName = this.name;
$scope.$broadcast('CharacterChanged', this.name);
};
$scope.$on('CharacterDeleted', function (event, removeName) {
var i = $scope.names.indexOf(removeName);
$scope.names.splice(i, 1);
$scope.currentName = $scope.names[0];
$scope.$broadcast('CharacterChanged', $scope.currentName);
});
})
.controller('Character', function ($scope) {
$scope.info = {
'Alan': {
weapon: 'Calculator',
job: 'Police Officer'
},
'Terry': {
weapon: 'Gun',
job: 'Police Officer'
},
'Gene': {
weapon: 'None',
job: 'Police Captain'
},
'Sheila': {
weapon: 'None',
job: 'M D'
},
'Danson': {
weapon: 'Gun',
job: 'Police Detective'
},
'Highsmith': {
weapon: 'Gun',
job: 'Police Detective'
},
'Bob': {
weapon: 'None',
job: 'Police Accountant'
}
};
$scope.currentInfo = $scope.info['Alan'];
$scope.$on('CharacterChanged', function (event, newCharacter) {
$scope.currentInfo = $scope.info[newCharacter];
});
$scope.deleteChar = function () {
delete $scope.info[$scope.currentName];
$scope.$emit('CharacterDeleted', $scope.currentName);
};
});
</script>
</body>
This is the ($http) controller I wrote.
angular.module('polarisApp')
.controller('MainCtrl', function ($scope, $http) {
$http.get('character.json')
.success(function(data) {
$scope.characterStatus = data.caracterStatus;
});
You can try this
var info = null;
$http.get('character.json').success(function(data) {
info = data;
});
The response from the $http.get request will be the object contained in content.json file. If you need to access Alan's job, you can use info.Alan.job and so on.
I got it working with this controller:
App.controller('CharacterCtrl', function($scope, $http) {
$http.get('characters.json')
.then(function(res){
$scope.characters = res.data;
}); });
Thank you very much for your feedback. I haven't seen that variable you used in any similar controllers. I think I should look into it--Might be missing out on a better way to $http. Thanks.

Cordova: Data that is filled inside array could not populate on page

I am not able to populate data filled inside the array.
My main controller front is this:
<body ng-controller="MainCtrl"> // MainCtrl controller
<ion-nav-view animation="slide-left-right"></ion-nav-view>
<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/owl.carousel.min.js"></script>
</body>
the MainCtrl initially contain nothing like this:
.controller('MainCtrl', function($scope, $ionicSideMenuDelegate, $ionicPopover, $state, $timeout) {
$scope.users = [];
$scope.devices = [];
})
Initially when i do login the controller named intro is getting called that controller calls rest & validate user & on successfully validating it does following:
.success(function(data, status, headers, config) {
if (data.alert === 'SUCCESS'){
var UserData = data.userdata;
var Username = UserData.personal_information.first_name+" "+UserData.personal_information.last_name;
var Email = UserData.username;
var LastLogin = new Date(UserData.last_visited * 1000);
$scope.users = [{ username: Username, email: Email, location: true, id: null, avatar: 'img/men.jpg', enabled: 'true', lastLogin: LastLogin}];
if(data.ownteam == true) {
$.each(data.ownteamdata, function( index, value ){
var TeamId = value.team_id;
var TeamName = value.team_name;
var Status = value.role;
var surveyArray = {id : TeamId, name :TeamName, icon: 'ion-document-text', status : Status, color : Color};
$scope.devices.push(surveyArray);
});
}
now when i console the array it shows me the data inserted.
then i move to dashboard page where the data of devices array need to be polupated & shown like:
<div ng-repeat="device in devices | filter: { featured: true}">
<div class="padding-horizontal">
<div class="item item-icon-left" on-tap="deviceTap('router.device', device)">
<i class="icon" ng-class="device.icon"></i>
{{ device.name }}
<span class="badge" ng-class="device.color">
{{ device.status }}
</span>
</div>
</div>
</div>
but it is not showing the data to me in the page??? is there something i m missing?
You're trying to filter the devices where featured = true
<div ng-repeat="device in devices | filter: { featured: true}">
but you don't seem to have that element in your object:
var surveyArray = {
id : TeamId,
name :TeamName,
icon: 'ion-document-text',
status : Status,
color : Color
};
Another problems could be the fact that you're maybe - trying to access the array from 2 different controllers.
I would suggest to check your console in chrome (F12) and use some sort of debug.
UPDATE:
One approach if you want to share data between controllers is to use a shared service, like a session, so you can move of the login for the login and validation there (clean controllers).
You can have a look at this plunker.
In app.services.js you will find a service called userAccountService.
(function () {
'use strict';
var services = angular
.module('app.services', [])
.factory('userAccountService', userAccountService);
userAccountService.$inject = ['$q'];
function userAccountService($q) {
var service = {
users: [],
devices: [],
logIn: logIn,
};
return (service);
function logIn(username, password)
{
var deferred = $q.defer();
this.users.push({username: username});
this.devices = [{name: 'android'}, {name: 'iphone'}];
deferred.resolve({users: this.users, devices: this.devices });
return deferred.promise;
}
};
})();
It will be responsible for the log-in an for sharing data between controllers ... and other modules. It is a singleton.
This service contains 2 arrays: users and devices:
var service = {
users: [],
devices: [],
logIn: logIn
};
The login method will, presumably, authenticate the user through an http call and will populate the shared members: users and devices.
(I've used promises there to match your $http call).
Now you can have a look at the app.controller.js file where my controllers are defined.
They depend on userAccountService.
view1Controller is the starting point and it is in charge for the login:
$scope.login = function()
{
userAccountService.logIn('username', 'password')
.then(function(result){
$scope.users = result.users,
$scope.devices = result.devices
})
.catch(function(reason){
console.log(reason);
});
$state.go('view2');
}
if the login is successful it will populate the two local members to be displayed in the page.
<div ng-repeat="device in devices">
<div class="padding-horizontal">
<div class="item item-icon-left">
{{ device.name }}
</span>
</div>
</div>
</div>
Same thing happens with view2. Now we don't need to login again; we can simply read the shared member of our service:
.controller('view2Controller', function($scope, userAccountService) {
$scope.users = [];
$scope.devices = [];
function init()
{
$scope.users = userAccountService.users;
$scope.devices = userAccountService.devices;
}
init();
})

displaying data from Firebase with angular

I am trying to display a table of posts following this tutorial:
http://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-angularjs-and-firebase--cms-22391
Part 5 has still not been published, so I took the tutorial all the way to part 4 and am trying to build a post.html view. However, as a beginner in both angular and firebase, I am really struggling.
Here is the code for my post/post.js file:
'use strict';
angular.module('myApp.post', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/post', {
templateUrl: 'post/post.html',
controller: 'PostCtrl'
});
}])
.controller('PostCtrl', ['$scope','$firebase' , function($scope,$firebase) {
$scope.message = 'Hello World';
$scope.viewPost = function(){
$scope.article.title = "";
$scope.article.post = "";
$scope.article= {};
$scope.myData = new Firebase("https://glowing-fire-6133.firebaseio.com/Posts");
};
$scope.myData.on('value', function(snapshot){
$scope.article = snapshot.val();
});
}]);
And here is the code for my post.html file
<title></title>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/blog.css" rel="stylesheet">
</head>
<body ng-controller="PostCtrl">
<h1>{{message}}</h1>
<div ng-repeat="post in posts">
<h2>{{article.title}}</h2>
<div>{{article.post}}</div>
</div>
</body>
</html>
I get no errors or results from this. I made sure to add the
'myApp.post', //Post view
module to app.js and the in the index.html but still nothing.
Am I doing or missing something really stupid? I.E. login to the DB etc.?
Thanks for your patience
##Addpost script
'use strict';
angular.module('myApp.addPost', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/addPost', {
templateUrl: 'addPost/addPost.html',
controller: 'AddPostCtrl'
});
}])
.controller('AddPostCtrl', ['$scope','$firebase',function($scope,$firebase) {
$scope.AddPost = function(){
var title = $scope.article.title;
var post = $scope.article.post;
var firebaseObj = new Firebase("https://glowing-fire-6133.firebaseio.com/Posts");
var fb = $firebase(firebaseObj);
fb.$push({ title: title,post: post}).then(function(ref) {
console.log(ref);
}, function(error) {
console.log("Error:", error);
});
}
}]);
Where is $scope.posts? I don't see it in your controller, so there's nothing to loop through.
You should have $scope.posts = [/* a bunch of post objects*/];
I actually kinda looks like you should be doing <div ng-repeat="post in myData">.

Creating custom service in Angular using MeanJS

Still very new to MeanJS and Angular, but am trying to get a repeater to use a custom node service that i created
Here is the Angular Template
<section data-ng-controller="AppController">
<section data-ng-controller="GroupsController" data-ng-init="findMyItems()">
<div class="page-header">
<h1>My Groups</h1>
</div>
<div class="list-group">
<a data-ng-repeat="group in groups" data-ng-href="#!/groups/{{group._id}}" class="list-group-item">
<small class="pull-right" data-ng-bind="group.shortId"></small>
<h4 class="list-group-item-heading" data-ng-bind="group.name"></h4>
<small class="list-group-item-text">
Posted on
<span data-ng-bind="group.created | date:'medium'"></span>
by
<span data-ng-bind="group.user.displayName"></span>
</small>
</a>
</div>
<div class="alert alert-warning text-center" data-ng-hide="!groups.$resolved || groups.length">
No Groups yet, why don't you create one?
</div>
</section>
</section>
Here is an array of JSON objects returned from localhost:3000/users/me/groups
[
{
_id: "5407dd31594e810000af4fa0",
user: "5407c78f9ef3025bbf0440f7",
description: "Activating....",
__v: 0,
projects: [ ],
created: "2014-09-04T03:32:01.825Z",
shortId: "bkXtE746M",
name: "Wonder Twins"
},
{
_id: "5407dc49a34a610000af6896",
user: "5407c78f9ef3025bbf0440f7",
description: "Loved watching this one",
__v: 0,
projects: [ ],
created: "2014-09-04T03:28:09.480Z",
shortId: "WJejxZorTz",
name: "Fantastic Four"
},
{
_id: "5407d71839c7de000008cf6b",
user: "5407c78f9ef3025bbf0440f7",
description: "Great group",
__v: 0,
projects: [ ],
created: "2014-09-04T03:06:00.098Z",
shortId: "ZJfKDyN6f",
name: "Leaders of the New School"
}
]
Controller
'use strict';
// Groups controller
angular.module('groups').controller('GroupsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Groups', 'GroupsAPI',
function($scope, $stateParams, $location, Authentication, Groups, GroupsAPI ) {
$scope.authentication = Authentication;
$scope.findMyItems = function() {
GroupsAPI.getGroupsByCurrentUser()
.success(function (groups) {
$scope.groups = groups;
})
.error(function (error) {
$scope.status = 'Unable to load group data: ' + error.message;
});
};
}
]);
I'm not exactly sure what the service is doing in MeanJS
'use strict';
//Groups service used to communicate Groups REST endpoints
angular.module('groups').factory('Groups', ['$resource',
function($resource) {
return $resource('groups/:groupId', { groupId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
What I'd like to do is something like to do is something like bellow, but not sure if there is a better way
'use strict';
//Groups service used to communicate Groups REST endpoints
angular.module('groups').factory('Groups', ['$resource',
function($resource) {
return $resource('groups/:groupId', { groupId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
angular.module('groups')
.factory('GroupsAPI', ['$http', function($http) {
var GroupsAPI = {};
GroupsAPI.getGroupsByCurrentUser = function () {
return $http.get('users/me/groups');
};
return GroupsAPI;
}]);
Is there a better way of doing this the MeanJS way?
It's been a long time since you posted this, so you likely figured out a solution already, but for the sake of future readers I'll toss an answer in here.
If I'm understanding what you're trying to do, it looks like you are trying to create a custom factory that functions similar to the existing Groups factory (the one you mentioned you didn't know what it was doing). That's what I'll be answering...
To begin with, you'll want to read the Angular documentation on $resource: https://docs.angularjs.org/api/ngResource/service/$resource. This is what makes the Groups factory work.
To summarize, Angular's $resource allows you to make AJAX requests very easily, by allowing you to create a variable in your controller which has access to REST functions. So basically, you would do something like this:
// Groups controller
angular.module('groups').controller('GroupsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Groups', 'GroupsAPI',
function($scope, $stateParams, $location, Authentication, Groups, GroupsAPI ) {
$scope.authentication = Authentication;
// Since you've added 'Groups' as a dependency, you can now use this "resource" in a new variable.
var groups = new Groups({
// Set any object data you need here, or leave empty.
});
// Now that you have a new instance of your 'Groups' resource (i.e. 'groups'), you can use standard REST calls.
groups.get({
user: currentUser
}, function(results) {
// Do something with results here, e.g.
if(results) {
$scope.groups = results;
} else {
$scope.status = 'Unable to load group data.';
}
});
]);
Note: I haven't tested this code, but this is the idea.

Resources