how to inject componenet in angularjs - javascript

I am using meanjs(meanjs.org) boiler plate code to build my website and I want to implement file upload feature in the website.
I am using https://github.com/ghostbar/angular-file-model and installed the component and added into bower.json. How do I inject it into my application
Following is the usage written on the website
Install with bower:
bower install angular-file-model --save
Add to your HTML files:
<script src='/bower_components/angular-file-model/angular-file-model.js'></script>
Now, inject to your application:
angular.module('myApp', ['file-model']);
How do I inject in my app?
angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles',
function($scope, $stateParams, $location, Authentication, Articles) {
$scope.authentication = Authentication;
$scope.file = null;
$scope.$watch('file', function (newVal) {
if (newVal) console.log(newVal);
});
$scope.create = function() {
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
$scope.title = '';
$scope.content = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.remove = function(article) {
if (article) {
article.$remove();
for (var i in $scope.articles) {
if ($scope.articles[i] === article) {
$scope.articles.splice(i, 1);
}
}
} else {
$scope.article.$remove(function() {
$location.path('articles');
});
}
};
$scope.update = function() {
var article = $scope.article;
article.$update(function() {
$location.path('articles/' + article._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function() {
$scope.articles = Articles.query();
};
$scope.findOne = function() {
$scope.article = Articles.get({
articleId: $stateParams.articleId
});
};
}
]);
is my controller page. Which can be found at https://github.com/meanjs/mean
my view page is
<section data-ng-controller="ArticlesController" data-ng-init="find()">
<div class="page-header">
<h1>Articles</h1>
</div>
<form>
<input type='file' file-model='file'>
</form>
</section>

Related

Converting Angularjs to Vuejs

I am uplifting a chat application from AngularJS to VueJS and I don't have much clue about how the AngularJS. There isn't really a great resources available on AngularJS right now to gain some insight.
If someone could help me in this I'd really appreciate it.
I wish to convert this below AngularJS code to VueJS completely.
var app = angular.module('IBMfinder', ['ngRoute']);
app.config(['$routeProvider',
function($routeProvider, settings) {
$routeProvider
.when('/main', {
templateUrl: 'welcome.html',
controller: 'welcomeCtrl',
})
.when('/find', {
templateUrl: 'find.html',
controller: 'findCtrl',
})
.when('/chat', {
templateUrl: 'chat.html',
controller: 'chatCtrl',
})
.otherwise({
templateUrl: 'welcome.html',
controller: 'welcomeCtrl',
})
}])
app.controller('userCount', ['$scope', 'socket', function($scope,
socket){
socket.on('userCount', function(amount){
$scope.online = amount;
})
}]);
app.controller('welcomeCtrl', ['$scope', '$location', 'settings',
'socket', function($scope, $location, settings, socket){
$scope.users = 13;
if(settings.getUsername()!==""){
socket.emit('delete');
settings.reset();
}
$scope.enter = function(){
settings.setUsername($scope.name);
$location.path('/find');
}
}]);
app.controller('findCtrl', ['$scope', '$location', 'settings',
'socket', '$rootScope', function($scope, $location, settings,
socket, $rootScope){
$scope.username = settings.getUsername();
if(!$scope.username || $scope.username == ""){
location.href = "index.html";
}
if(settings.exists){
socket.emit('delete');
location.href = "index.html";
}
$scope.chatlog = [];
if(!settings.exists){
var username = $scope.username;
settings.setExists(true);
socket.emit('new user', username );
};
socket.on('match', function (data) {
settings.setPartner(data['username'], data['id']);
$location.path('/chat');
});
}]);
app.controller('chatCtrl', ['$scope', '$location', 'settings',
'socket', '$rootScope', '$timeout', '$window', '$interval',
function($scope, $location, settings, socket, $rootScope, $timeout,
$window, $interval){
var typing = false;
var focus = true;
var titleTimer;
var onFocus = function(){
focus = true;
$interval.cancel(titleTimer);
document.title = 'Chat-Box';
}
var onBlur = function(){
focus = false;
}
$window.onfocus = onFocus;
$window.onblur = onBlur;
$scope.username = settings.getUsername();
$scope.partnerTyping = false;
if(!$scope.username || $scope.username == ""){
location.href = "index.html";
}
$scope.chatlog = [];
if(!settings.exists){
var username = $scope.username;
settings.setExists(true);
socket.emit('new user', username );
};
socket.on('incoming message', function(data){
if($scope.chatlog[$scope.chatlog.length-1]){
if($scope.chatlog[$scope.chatlog.length-1].sentby == data.userID){
$scope.chatlog[ $scope.chatlog.length] = {
sentby:data.userID,
chatusername: '',
chatmessage: data.message
}
}else{
$scope.chatlog[ $scope.chatlog.length] = {
sentby:data.userID,
chatusername: data.user + ": ",
chatmessage: data.message
}
}
}else{
$scope.chatlog[ $scope.chatlog.length] = {
sentby:data.userID,
chatusername: data.user + ": ",
chatmessage: data.message
}
}
if(!focus){
document.title = 'New Message!';
$interval.cancel(titleTimer);
titleTimer = $interval(function(){
if(document.title == 'New Message!'){
document.title = 'Chat-Box';
}else{
document.title = 'New Message!';
}
}, 1000)
}
});
socket.on('aborted', function(data){
alert('Your partner left, sorry!');
socket.emit('delete');
settings.reset();
location.href = "index.html";
})
$scope.typing = function(){
if(!typing){
socket.emit('typing', settings.getID());
typing = true;
var stop = $timeout(function() {
typing = false;
socket.emit('stop typing', settings.getID());
}, 2000);
}
}
socket.on('typing', function(data){
$scope.partnerTyping = true;
$('#chatbox').scrollTop(10000);
})
socket.on('stop typing', function(data){
$scope.partnerTyping = false;
$('#chatbox').scrollTop(10000);
})
$scope.sendMessage = function(){
if($scope.message==""){
}else{
socket.emit( 'new message', {
message:$scope.message,
partner:$scope.partner,
partnerID: settings.getID()
});
}
$scope.message = "";
}
$scope.partner = settings.getPartner();
}]);
app.service('settings', function() {
this.exists = false;
this.username = "";
this.partner = "";
this.partnerID = "";
this.userdata = {}
this.setExists = function(bool){
this.exists = bool;
}
this.setUsername = function(uname){
this.username = uname;
}
this.getUsername = function(){
return(this.username);
}
this.setUserID = function(id){
this.userdata.id = id;
}
this.getuserdata = function(){
return(this.userdata);
}
this.setPartner = function(uname, id){
this.partner = uname;
this.partnerID = id;
}
this.getPartner = function(){
return(this.partner);
}
this.getID = function(){
return(this.partnerID);
}
this.reset = function(){
this.exists = false;
this.username = "";
this.partner = "";
this.partnerID = "";
this.userdata = {}
}
});
app.factory('socket', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
},
disconnect: function(id){
socket.disconnect(id);
}
};
});
app.directive('myEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.myEnter);
});
event.preventDefault();
}
});
};
});
app.directive('schrollBottom', function () {
return {
scope: {
schrollBottom: "="
},
link: function (scope, element) {
scope.$watchCollection('schrollBottom', function (newValue) {
if (newValue)
{
$(element).scrollTop(100000);
}
});
}
}
})
It'd be great if someone could point me to any great resources. I've not had any luck since past week regarding this.
Video Tutorials
https://www.youtube.com/watch?v=i9MHigUZKEM
https://egghead.io/courses/angularjs-fundamentals
Text Tutorials
https://docs.angularjs.org/tutorial
Try to search on google first.
If you can't understand something ask a concrete question with an example (it doesn't have to be the full code) so we can help you better.
I don't know if you have experience with Vue.js, I can tell you worse what those tutorials will explain way better. AngularJS uses a different approach than Vue, Angular 2+ or React.
Those frameworks use a component approach so you divide the app into multiple components that have properties.
Angular use an MVC-ish approach, you define modules with angular. module those modules can have external or core dependencies defined in the array.
A module can have a router, a router will define the views and the controller of each view. The views have angular directives and HTML, and the controllers have the logic.
Use one of those tutorials to learn more.

Send data through a POST request from Angular factory

I have this in the controller
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
$scope.formTodoText = '';
};
});
and this in the factory
angular.module('myApp')
.factory('TaskFactory', function ($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
console.log(1, params);
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log(2);
console.log('data', data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTask: function(taskData) {
console.log('taskData', taskData);
return sendTasks('/task/save', {
taskData : taskData
})
}
}
});
all I need is to know, how to send the data from the controller to the factory in order to do the POST to the specified route ?
You just need to call the function/method inside factory with the required params.
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
TaskFactory.sendTask({data : $scope.formTodoText})
$scope.formTodoText = '';
};
});
You can follow Dan Wahlin blog post.
Controller:
angular.module('customersApp')
.controller('customersController', ['$scope', 'dataFactory', function ($scope, dataFactory) {
$scope.status;
dataFactory.updateCustomer(cust)
.success(function () {
$scope.status = 'Updated Customer! Refreshing customer list.';
})
.error(function (error) {
$scope.status = 'Unable to update customer: ' + error.message;
});
}
Factory:
angular.module('customersApp')
.factory('dataFactory', ['$http', function($http) {
var urlBase = '/api/customers';
dataFactory.updateCustomer = function (cust) {
return $http.put(urlBase + '/' + cust.ID, cust)
};
}
Hope that solve your problem.
You can call the function directly on the TaskFactory that you pass into the controller as a dependency.
I've cleaned up your code a bit and created a plunk for you here:
And here's the code:
Controller
(function(angular) {
// Initialise our app
angular.module('myApp', [])
.controller('TaskController', function($scope, TaskFactory) {
// Initialise our variables
$scope.todos = [];
$scope.formTodoText = '';
$scope.addTodo = function() {
// Add an object to our array with a 'text' property
$scope.todos.push({
text: $scope.formTodoText
});
// Clear the input
$scope.formTodoText = '';
// Call function to send all tasks to our endpoint
$scope.sendTodos = function(){
TaskFactory.sendTasks($scope.todos);
}
};
});
})(angular);
Factory
(function(angular) {
angular.module('myApp')
.factory('TaskFactory', function($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log('data: ' + data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTasks: sendTasks
}
});
})(angular);

Firebase API issue with AngularJS website example project

Beginning to dive into AngularJS so I went to their website, but got stuck on the wire up a backend portion where Angular uses Firebase. The first issue came from the ordering of dependencies:
angular.module('project', ['ngRoute', 'firebase'])
changed to
angular.module('project', ['firebase', 'ngRoute'])
But now it's telling my that $add, in my $scope.save call, is undefined.
Similar $add undefined questions are here and here, but neither seem to apply.
Note: I'm running node's http-server, so I'm assuming it's not a localhost problem.
Scripts
angular.module('project', ['firebase', 'ngRoute'])
.value('fbURL', 'https://unique-url-yay.firebaseio.com/')
.service('fbRef', function(fbURL) {
return new Firebase(fbURL)
})
.service('fbAuth', function($q, $firebase, $firebaseAuth, fbRef) {
var auth;
return function () {
if (auth) return $q.when(auth);
var authObj = $firebaseAuth(fbRef);
if (authObj.$getAuth()) {
return $q.when(auth = authObj.$getAuth());
}
var deferred = $q.defer();
authObj.$authAnonymously().then(function(authData) {
auth = authData;
deferred.resolve(authData);
});
return deferred.promise;
}
})
.service('Projects', function($q, $firebase, fbRef, fbAuth) {
var self = this;
this.fetch = function () {
if (this.projects) return $q.when(this.projects);
return fbAuth().then(function(auth) {
var deferred = $q.defer();
var ref = fbRef.child('projects/' + auth.auth.uid);
var $projects = $firebase(ref);
ref.on('value', function(snapshot) {
if (snapshot.val() === null) {
$projects.$set(window.projectsArray);
}
self.projects = $projects.$asArray();
deferred.resolve(self.projects);
});
return deferred.promise;
});
};
})
.config(function($routeProvider) {
$routeProvider
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html',
resolve: {
projects: function (Projects) {
return Projects.fetch();
}
}
})
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.html'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'detail.html'
})
.otherwise({
redirectTo:'/'
});
})
.controller('ListCtrl', function($scope, projects) {
$scope.projects = projects;
})
.controller('CreateCtrl', function($scope, $location, Projects) {
$scope.save = function() {
Projects.projects.$add($scope.project).then(function(data) {
$location.path('/');
});
};
})
.controller('EditCtrl',
function($scope, $location, $routeParams, Projects) {
var projectId = $routeParams.projectId,
projectIndex;
$scope.projects = Projects.projects;
projectIndex = $scope.projects.$indexFor(projectId);
$scope.project = $scope.projects[projectIndex];
$scope.destroy = function() {
$scope.projects.$remove($scope.project).then(function(data) {
$location.path('/');
});
};
$scope.save = function() {
$scope.projects.$save($scope.project).then(function(data) {
$location.path('/');
});
};
});
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Angular</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js">
</script>
<script src="https://cdn.firebase.com/js/client/2.0.4/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.9.0/angularfire.min.js"></script>
<script src="scripts.js" type="text/javascript"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body style="padding:20px;">
<div ng-app="project" class="ng-scope"></div>
<div ng-view></div>
</body>
</html>
Alright, a few things are going on here:
Suggestions
AngularFire was updated to 1.1.1 and $firebase is now deprecated. Use $firebaseObject and $firebaseArray instead.
There is no need to do all that stuff in your Projects service and return a promise. $firebaseObject and $firebaseArray return promises.
Example
Check out this PLNKR I made showing a working version of what you're trying to accomplish.
It's tied to one of my public Firebase instances.
You can create a new piece of data and see it on the home page.
JavaScript:
(function(angular) {
angular.module('project', ['firebase', 'ngRoute'])
.value('fbURL', 'https://sb-plnkr.firebaseio.com/so:28942661')
.service('fbRef', function(fbURL) {
return new Firebase(fbURL)
})
.service('fbAuth', function($q, $firebaseAuth, fbRef) {
var auth;
return function () {
if (auth) return $q.when(auth);
var authObj = $firebaseAuth(fbRef);
if (authObj.$getAuth()) {
return $q.when(auth = authObj.$getAuth());
}
var deferred = $q.defer();
authObj.$authAnonymously().then(function(authData) {
auth = authData;
deferred.resolve(authData);
});
return deferred.promise;
}
})
.service('Projects', function($q, $firebaseArray, fbRef) {
this.sync = $firebaseArray(fbRef);
this.sync.$loaded().then(function(data) {
var projects = data;
});
return this.sync;
})
.controller('ListCtrl', function($scope, $location, Projects) {
Projects.$loaded().then(function(data){
$scope.projects = data;
});
})
.controller('CreateCtrl', function($scope, $location, Projects) {
console.log("CreateCtrl");
$scope.save = function() {
console.debug("Adding");
if ($scope.project && $scope.project.content !== '') {
Projects.$add($scope.project).then(function(ref) {
console.log("Added ref",ref);
$location.path('/');
}).catch(function(errorObject){
console.error(errorObject);
});
} else {
alert("You have to enter something.");
}
};
})
.controller('EditCtrl',function($scope, $location, $routeParams, Projects) {
var projectId = $routeParams.projectId,
projectIndex;
$scope.init = function(){
Projects.$loaded().then(function(data) {
$scope.projects = data;
console.info("EditCtrl - Projects.$loaded():",data);
projectIndex = $scope.projects.$indexFor(projectId);
$scope.project = $scope.projects[projectIndex];
});
}
$scope.destroy = function() {
$scope.projects.$remove($scope.project).then(function(data) {
$location.path('/');
});
};
$scope.save = function() {
$scope.projects.$save($scope.project).then(function(data) {
$location.path('/');
});
};
})
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html'
})
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.html'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'create.html'
})
.otherwise({
redirectTo:'/'
});
$locationProvider.html5Mode(true);
});
})(window.angular);
HTML:
(index.html)
<body style="padding:20px;">
<div ng-app="project" ng-controller="EditCtrl">
New
<div ng-view></div>
</div>
</body>
(create.html)
<h2>Create</h2>
<button ng-click="save()">Save</button>
(list.html)
<h2>List</h2>
<div ng-repeat="(key,data) in projects">
<span>$scope.projects[<span ng-bind="key"></span>].content : </span>
<span ng-bind="data.content"></span>
</div>
<h2>Object Debug</h2>
<pre ng-bind="projects | json"></pre>
Hope that helps!

'book' is defined but never used MEAN stack controller

I'm having problems creating a variable and using it in a MEAN package. I'm basing it off of the "articles" package that comes as an example. Everything I see is the same in the client-side controller, but I'm not sure why I'm catching the error when I try to start my app (with grunt) on the "books" package but not the "articles" package.
I have not implemented all the controllers that articles has yet, that may be an issue?
When I start the app with grunt, I get this error on : 'book' is defined but never used MEAN stack controller
I believe the error is in the controller, but if you need to see other files please let me know.
books.js
//client-side controller
'use strict';
angular.module('mean.books').controller('BooksController', ['$scope', 'Global', 'Books',
function($scope, Global, Books) {
$scope.global = Global;
$scope.package = {
name: 'books'
};
$scope.hasAuthorization = function(book) {
if (!book || !book.user) return false;
return $scope.global.isAdmin || book.user._id === $scope.global.user._id;
};
$scope.create = function(isValid) {
if (isValid) {
var book = new Books({
title: this.title,
author: this.author,
description: this.description,
seller: this.seller
});
/* Not sure if we need this location thing
book.$save(function(response) {
$location.path('books/' + response._id);
});
*/
this.title = '';
this.content = '';
this.description = '';
this.seller = ''; // or this.user implement
} else {
$scope.submitted = true;
}
};
}
]);
articles.js //this is the example that I'm basing it from
'use strict';
angular.module('mean.articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Global', 'Articles',
function($scope, $stateParams, $location, Global, Articles) {
$scope.global = Global;
$scope.hasAuthorization = function(article) {
if (!article || !article.user) return false;
return $scope.global.isAdmin || article.user._id === $scope.global.user._id;
};
$scope.create = function(isValid) {
if (isValid) {
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
});
this.title = '';
this.content = '';
} else {
$scope.submitted = true;
}
};
$scope.remove = function(article) {
if (article) {
article.$remove(function(response) {
for (var i in $scope.articles) {
if ($scope.articles[i] === article) {
$scope.articles.splice(i, 1);
}
}
$location.path('articles');
});
} else {
$scope.article.$remove(function(response) {
$location.path('articles');
});
}
};
$scope.update = function(isValid) {
if (isValid) {
var article = $scope.article;
if (!article.updated) {
article.updated = [];
}
article.updated.push(new Date().getTime());
article.$update(function() {
$location.path('articles/' + article._id);
});
} else {
$scope.submitted = true;
}
};
$scope.find = function() {
Articles.query(function(articles) {
$scope.articles = articles;
});
};
$scope.findOne = function() {
Articles.get({
articleId: $stateParams.articleId
}, function(article) {
$scope.article = article;
});
};
}
]);
In $scope.create function you defined book
var book = new Books({
and never use it. That's reason you get warning. If you want to skip jshint warnings in development use grunt -f or allow unused variables in your grunt configuration (or .jshintrc if you use it)

Inputting an UUID/GUID into a form's text input using Angular JS

I am creating a form with several input options for the end user, but with one input which I would like to be an UUID/GUID.
Here's what I have so far for the module (project.js):
angular.module('project', ['ngRoute', 'firebase'])
.value('fbURL', 'https://private.firebaseio.com/')
.factory('Projects', function($firebase, fbURL) {
return $firebase(new Firebase(fbURL));
})
.config(function($routeProvider) {
$routeProvider
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html'
})
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.php'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'detail.php'
})
.otherwise({
redirectTo:'/'
});
})
.controller('ListCtrl', function($scope, Projects) {
$scope.projects = Projects;
$scope.project = { trackid: 'UUID' };
})
.controller('CreateCtrl', function($scope, $location, $timeout, Projects) {
$scope.project = { trackid: 'UUID' };
$scope.save = function() {
Projects.$add($scope.project, function() {
$timeout(function() { $location.path('/'); });
});
};
})
.controller('EditCtrl',
function($scope, $location, $routeParams, $firebase, fbURL) {
var projectUrl = fbURL + $routeParams.projectId;
$scope.project = $firebase(new Firebase(projectUrl));
$scope.destroy = function() {
$scope.project.$remove();
$location.path('/');
};
$scope.save = function() {
$scope.project.$save();
$location.path('/');
};
$scope.project = { trackid: 'UUID' };
});
And here's what I have for the form input (in my detail.php file):
<form name="myForm">
<label>Track ID</label>
<input type="text" name="trackid" ng-model="project.trackid" disabled>
As you can tell, in this example I'm simply inserting the text "UUID" where I would actually like to insert an UUID. I can't however seem to figure out how to insert a function there that would be generating this UUID. Any help would be very much appreciated! Thank you!
If you have a function that returns the value needed you can simply do:
function getUUID(){
var result = /* parse value */
return result;
}
$scope.project ={ trackid: getUUID() };
DEMO

Categories

Resources