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)
Related
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.
I am trying to get a angular modal form working but I am always getting an unknown provider error. I think I have included all the necessary files?
Here is my code for calling the service:
function deleteConfirm() {
var modalOptions = {
closeButtonText: 'Cancel',
actionButtonText: 'Delete Supplier',
headerText: 'Delete ' + supplierName + '?',
bodyText: 'Are you sure you want to delete this supplier?'
};
modalService.showModal({}, modalOptions).then(function(result) {
if (result === 'ok') {
alert("ok");
}
}, function(error) {
alert("Error deleting");
});
}
And here is the code for the service:
(function() {
'use strict';
modalService.$inject = '$uibModal';
angular.module('plunker').factory('modalService', modalService);
function modalService($uibModal) {
var injectParams = ['$uibModal'];
//var modalService = function($uibModal) {
var modalDefaults = {
backdrop: true,
keyboard: true,
modalFade: true,
templateUrl: 'modal.html'
};
var modalOptions = {
closeButtonText: 'Close',
actionButtonText: 'OK',
headerText: 'Proceed?',
bodyText: 'Perform this action?'
};
this.showModal = function(customModalDefaults, customModalOptions) {
if (!customModalDefaults) customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return this.show(customModalDefaults, customModalOptions);
};
this.show = function(customModalDefaults, customModalOptions) {
//Create temp objects to work with since we're in a singleton service
var tempModalDefaults = {};
var tempModalOptions = {};
//Map angular-ui modal custom defaults to modal defaults defined in this service
angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);
//Map modal.html $scope custom properties to defaults defined in this service
angular.extend(tempModalOptions, modalOptions, customModalOptions);
if (!tempModalDefaults.controller) {
tempModalDefaults.controller = function($scope, $uibModalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.ok = function(result) {
$uibModalInstance.close('ok');
};
$scope.modalOptions.close = function(result) {
$uibModalInstance.close('cancel');
};
};
tempModalDefaults.controller.$inject = ['$scope', '$uibModalInstance'];
}
return $uibModal.open(tempModalDefaults).result;
};
}
}());
http://plnkr.co/edit/xNpbI42UJm8acODSOimR
Thanks for any help
angular.module('plunker').factory('modalService', modalService);
modalService.$inject = ['$uibModal'];
Try this!
Add to main app.js dependencies ['ui.bootstrap']
var app = angular.module('plunker', ['ui.bootstrap']);
You forgot to include "ui.bootstrap" into your app.
Simply bootstrap your app like this to correct the issue :
var app = angular.module('plunker', ["ui.bootstrap"]);
I'm trying to setup a restful API interface via AngularJS with the following code:
'use strict';
(function(angular) {
function ApiAction($resource, ResourceParameters) {
return $resource(ResourceParameters.route,
{ },
{ api_index: {
method: ResourceParameters.method,
isArray: true
}
});
return $resource(ResourceParameters.route,
{ },
{ create: {
method: ResourceParameters.method,
isArray: true
}
}
);
}
function ResourceParameters($scope) {
var factory = {};
factory.method = '';
factory.route = '';
factory.SetMethod = function(method) {
factory.method = method;
}
factory.SetRoute = function(route) {
factory.route = route;
}
return factory;
}
function superheroCtr($scope, ApiAction, ResourceParameters) {
$scope.superheroSubmit = function() {
// ApiAction.create({}, { superhero_name: $scope.superheroName, age: $scope.superheroAge });
angular.forEach($scope.superheroes, function(hero) {
// ApiAction.create({}, { superhero_name: hero.superhero_name, age: hero.age });
});
};
var heroesResources = ResourceParameters($scope).SetRoute('/api/');
var heroes = ApiAction.api_index({}, heroesResources);
$scope.superheroes = [];
heroes.$promise.then(function(data) {
angular.forEach(data, function(item) {
$scope.superheroes.push(item);
});
}, function(data) {
//if error then...
});
$scope.appendSuperheroFields = function() {
var i = $scope.superheroes.length + 1;
$scope.superheroes.push({"id": i, age: "", superhero_name: "" })
}
}
var superheroApp = angular.module('superheroApp', ['ngResource']);
superheroApp.controller('superheroCtr', ['$scope', 'ApiAction', 'ResourceParameters', superheroCtr]);
superheroApp.factory('ResourceParameters', ['$scope', ResourceParameters]);
superheroApp.factory('ApiAction', ['$resource', ResourceParameters, ApiAction]);
})(angular);
Yet, when I run it I get the following error:
Error: [$injector:itkn] Incorrect injection token! Expected service name as string, got function ResourceParameters($scope)
Why is this?
Simply you can not inject $scope OR you can not have access to $scope
inside a factory
Your problem is at this line
superheroApp.factory('ResourceParameters', ['$scope', ResourceParameters]);
You need to replace that line with
superheroApp.factory('ResourceParameters', [ResourceParameters]);
Factory
function ResourceParameters() { //<--removed $scope from here
var factory = {};
factory.method = '';
factory.route = '';
factory.SetMethod = function(method) {
factory.method = method;
}
factory.SetRoute = function(route) {
factory.route = route;
}
return factory;
}
Update
Additionally you should correct the declaration of ApiAction where ResourceParameters should be placed inside ' single qoutes
superheroApp.factory('ApiAction', ['$resource', 'ResourceParameters', ApiAction]);
I am trying to create a tag layout filled with categories, but I am not getting my Authentication because I am trying to resolve that service in my Router.
this is my Router code
(function () {
'use strict';
angular
.module('learningApp')
.config(sslRouter);
// Minification safe dependency Injection
sslRouter.$inject = ['$stateProvider'];
function sslRouter ($stateProvider) {
// SSL Route Definition
$stateProvider.state('ssl', {
parent: 'policy',
url: '/ssl',
data: {
roles: ['USER']
},
views: {
'policyConfig': {
templateUrl: 'components/configuration/service/policy/ssl/ssl.tpl.html',
controller: 'SSL'
}
},
resolve: {
'sslServiceData': function(sslService) {
return sslService.promise;
}
}
});
}
}());
This is my Service
(function() {
'use strict';
angular
.module('learningApp')
.factory('sslService', sslResource);
sslResource.$inject = ['Principal', '$resource', 'BASE_URL', 'exDomainService'];
function sslResource (Principal, $resource, BASE_URL, exDomainService) {
debugger;
var res = $resource(BASE_URL + '/api/companies/' + Principal.company() + '/sconfig/ssl/sslConfiguration', {}, {
query: {
method: 'GET',
isArray: false
},
update: {
method: 'PUT'
}
});
var data = {};
var servicePromise = _initService();
servicePromise.$promise.then(function (d) {
data = d;
if (!data.excludedCategories) {
data.excludedCategories = [];
}
if (!data.excludedDomains) {
data.excludedDomains = [];
}
exDomainService.tableData = getExcludedDomains();
});
function _initService () {
return res.query();
}
return {
promise: servicePromise,
rest: res
}
}
}());
This is my controller
(function() {
'use strict';
angular
.module('learningApp')
.controller('SSL', SSLController);
SSLController.$inject = ['$scope', 'sslService', 'preDefinedCategoryService', '$timeout', 'exDialog', 'exDomainService'];
function SSLController ($scope, sslService, preDefinedCategoryService, $timeout, exDialog, exDomainService) {
var vm = $scope;
/**
* #desc Flags for different type checks
* Booleans and Categories
*/
vm.flags = {
// By default true
enableInspectSSLTraffic: sslService.getSSlInspectionFlag(),
allowUntrustedCertificates: sslService.getUntrustedCertificatesFlag(),
allowHostnameMismatch: sslService.getHostnameMismatchFlag(),
selectedCategory: undefined,
initializing: true
};
vm.excludedCategories = sslService.getExcludedCategories();
vm.predefinedCategories = preDefinedCategoryService.rest.query();
vm.predefinedCategories.$promise.then(function() {
vm.categories = _processedCategories(vm.predefinedCategories, vm.excludedCategories);
});
}
}());
So basically problem is, I am getting Principal.Identity as undefined, but if I remove resolution from Router, I got identity but then I lose my data coming from service. I want my service to be loaded completely before its Controller, and I want my principal service to be loaded before service.
for Reference, This is my Principal Class
'use strict';
angular.module('learningApp')
.service('Principal',['$q', 'Account', 'localStorageService', function Principal($q, Account, localStorageService) {
var _identity,
_authenticated = false;
return {
isIdentityResolved: function () {
return angular.isDefined(_identity);
},
isAuthenticated: function () {
return _authenticated;
},
isInRole: function (role) {
if (!_authenticated || !_identity || !_identity.roles) {
return false;
}
return _identity.roles.indexOf(role) !== -1;
},
isInAnyRole: function (roles) {
if (!_authenticated || !_identity.roles) {
return false;
}
for (var i = 0; i < roles.length; i++) {
if (this.isInRole(roles[i])) {
return true;
}
}
return false;
},
company: function () {
debugger;
if (_identity) return _identity.companyId;
},
authenticate: function (identity) {
_identity = identity;
_authenticated = identity !== null;
},
identity: function (force) {
var deferred = $q.defer();
if (force === true) {
_identity = undefined;
}
// check and see if we have retrieved the identity data from the server.
// if we have, reuse it by immediately resolving
if (angular.isDefined(_identity)) {
deferred.resolve(_identity);
return deferred.promise;
}
// rather than retrieving from server, use cookie or whatever method
var cookieFound = UTIL.cookie("token");
if (cookieFound) {
var response = JSON.parse(JSON.parse(cookieFound));
var expiredAt = new Date();
expiredAt.setSeconds(expiredAt.getSeconds() + response.expires_in);
response.expires_at = expiredAt.getTime();
localStorageService.set('token', response);
}
// retrieve the identity data from the server, update the identity object, and then resolve.
Account.get().$promise
.then(function (account) {
account.data.roles = ["ADMIN", 'USER'];
account.data.langKey = "en";
_identity = account.data;
_authenticated = true;
deferred.resolve(_identity);
})
.catch(function() {
_identity = null;
_authenticated = false;
deferred.resolve(_identity);
});
return deferred.promise;
}
};
}]);
In my AngularJs application i am trying to use localStorage service, I have made reference of "angular-local-storage.js" and injected service in to module
var app = angular.module('SampleApp', ['ngRoute', 'ngSanitize', 'toaster', 'LocalStorageModule']);
When I am trying to consume service in my one of controller its throwing error.
(function () {
var app = angular.module('SampleApp');
app.controller('loginController', ['$scope', 'notificationFactory', '$location', 'HTMLEditorService', '$rootScope', '$q', 'localStorageService',
function ($scope, notificationFactory, $location, HTMLEditorService, $rootScope, $q, localStorageService) {
var _authentication = {
isAuth: false,
userName: ""
};
$scope.bind = function (data) {
if (data.status) {
if (data.Metadata.ErrorMessage == null || data.Metadata.ErrorMessage.trim() == '') {
if (data.Metadata.AuthToken == null || data.Metadata.AuthToken.trim() == '') {
notificationFactory.error("User authentication failed. Please try again.");
}
else {
var deferred = $q.defer();
localStorageService.set('authorizationData', { userName: data.Data.UserName });
_authentication.isAuth = true;
_authentication.userName = data.Data.userName;
deferred.resolve(response);
notificationFactory.success('User logged-in successfully!');
$rootScope.isLoggedIn = true;
$location.url('/LandingPage');
}
}
else {
notificationFactory.error(data.Metadata.ErrorMessage);
}
} else {
notificationFactory.error('Server Error. Please try again.');
}
}
$scope.userLogin = function () {
try {
if (loginValidation(this.userName, this.password)) {
var request = new Object();
request.Metadata = new Object();
request.Data = new Object();
request.Metadata.SecurityGroupId = 1;
request.Data.UserName = this.userName;
request.Data.Password = this.password;
HTMLEditorService.userLogin(request)
.then($scope.bind);
}
else {
notificationFactory.error('Invalid credentials');
}
} catch (e) {
notificationFactory.error('Error! Please try again.');
console.log(e);
}
}
$scope.cancelLogin = function () {
try {
this.userName = '';
this.password = '';
$location.url("/Login");
} catch (e) {
notificationFactory.error('Error! Please try again.');
}
}
$rootScope.isLoggedIn = false;
}]);
}());
Error Thrown:
ReferenceError: isUndefined is not defined
Any suggestion is highly appriciated.
Thanks in advance
See github issue here.
In short, you're probably referencing the version from their home page, which doesn't include the line at the top
var isDefined = angular.isDefined
The solution is to use the version from github or, preferably, install using bower
bower install angular-local-storage --save
I had the same problem.
I solved it by adding the prefix "angular." to isObject, isUndefined, isArray and isNumber within the angular-local-storage.js:
angular.isObject,
angular.isUndefined
...