I'm new in AngularJs. I just started learning dependencies concept.but i got problem when separated file between app.js and formapp.js. I cannot access users variable because its separated files.How can i access the variable?.I hope you guys can help me solve this problem.Thank you in advance.
index.html
<!DOCTYPE html>
<html ng-app="training">
<head>
<link rel="stylesheet" type="text/css" href="../bootstrap.min.css" />
<script type="text/javascript" src="../angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="formapp.js"></script>
<link rel="stylesheet" href="../style.css" />
</head>
<body ng-controller="UserController as usersCtrl">
<h3>User Information</h3>
<div ng-repeat="user in usersCtrl.mUsers">
<p><ul>
<li>{{user.name}}</li>
<li>{{user.age}}</li>
<li>{{user.occupation}}</li>
</ul></p>
</div>
<form-Directive></form-Directive>
</body>
</html>
app.js
(function(){
var app = angular.module('training',['form']);
app.controller('UserController',function(){
this.mUsers = users;
});
var users = [{
name:"michael",
age:"27",
occupation:"business"
},{
name:"john",
age:"25",
occupation:"police"
}];
})();
formapp.js
(function(){
var app = angular.module("form",[]);
app.directive('formDirective', function(){
return{
restrict: 'E',
templateUrl: 'user-form-directive.html',
controller:function(){
this.newUser = {};
this.addUser = function(){
users.push(this.newUser); //<-- users is not defined
this.newUser = {};
};
},
controllerAs: 'formCtrl'
};
});
})();
You can pass mUsers as an attribute to your element directive - formDirective.
index.html
<form-Directive users='mUsers'></form-Directive>
formapp.js
(function(){
var app = angular.module("form",[]);
app.directive('formDirective', function(){
return{
restrict: 'E',
templateUrl: 'user-form-directive.html',
scope: {
users: '='
},
controller:['$scope', function($scope){
this.newUser = {};
this.addUser = function(){
$scope.users.push(this.newUser); //<-- users is not defined
this.newUser = {};
};
}]
};
});
})();
Related
I am facing problem while opening JW Player 8 in modal in Angular JS.
Home.html
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="../Scripts/AngularControllers/HomeController.js"></script>
<script src="../Scripts/Libraries/JWPlayer/jwplayer.js"></script>
<script>jwplayer.key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"</script>
<script src="../Scripts/AngularControllers/VideoController.js"></script>
</head>
<body ng-app="appHome">
<div ng-repeat="today in todayList">
<img ng-src="{{today.image}}" ng-click="showVideo(today.desc)">
</div>
</body>
</html>
HomeController.js
var homeApp = angular.module("appHome", ['ui.bootstrap']);
homeApp.controller("ctrlHome", ['$scope', '$uibModal', function ($scope, $uibModal) {
$scope.todayList = [
{ image: 'Images/hqdefault.jpg', name: 'ABC ABC ', desc: 'Here I Am ' },
{ image: 'Images/hqdefault.jpg', name: 'DEF', desc: 'I will Rock' }
];
$scope.showVideo = function (videoId) {
var modalInstance = $uibModal.open({
templateUrl: 'Video.html',
controller: 'ctrlVideo',
size: 'lg',
resolve: {
videoId: function () {
return videoId;
}
}
})
}
}]);
Video.html
<div id="myElement"></div>
VideoController.js
var myApp = angular.module('appHome');
myApp.controller("ctrlVideo", ['$scope', 'videoId', function ($scope, videoId) {
var playerInstance = jwplayer("myElement");
playerInstance.setup({
file: "FileName",
width: 640,
height: 360
});
}]);
I am getting below error:-
TypeError: playerInstance.setup is not a function↵
After further analysis I found that Jwplayer is not able to find "<div id="myElement"></div>" mentioned in Video.html inside VideoController.js page.
Please help to resolve the error.
Finally I got answer to this. It was pretty clear after analysis that when VideoController.js is called up then at that point of time "myElement" defined in Video.html didn't loaded up. So I have to use something equivalent of document.ready in Angular JS and I modified VideoController.js as below:-
var myApp = angular.module('appHome');
myApp.controller("ctrlVideo", ['$scope', 'videoId', '$timeout', function ($scope, videoId, $timeout) {
$timeout(function () {
var playerInstance = jwplayer("myElement");
playerInstance.setup({
file: "FileName",
width: 640,
height: 360
});
});
}]);
var app = angular.module("Signup", ['ngRoute', "ngAnimate"]);
app.config(function($routeProvider) {
$routeProvider
.when('/signup', {
templateUrl: "/views/signup.html",
controller: "FormCtrl"
})
.when('/otp', {
templateUrl: "/views/otp.html",
controller: "FormCtrl"
})
.when('/password', {
templateUrl: "/views/password.html",
controller: "FormCtrl"
})
.when('/identity', {
templateUrl: "/views/identity.html",
controller: "FormCtrl"
})
.otherwise({
redirectTo: '/signup'
});
});
app.controller("FormCtrl", [function() {
var store = this;
store.usersData = [];
store.newuser = {
};
this.submit = function() {
store.usersData.push(store.newuser);
console.log(store.usersData);
store.newuser = {};
};
}]);
I have four templates sitting inside my views folder, namely, otp.html, password.html, identity.html, signup.html
And I have an index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<base href="/index.html">
<title>Sign Up | Rupaiya Exchange</title>
<link rel="stylesheet" href="assets/icons/font-awesome-4.7.0/css/font-awesome.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="assets/css/signupform.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-animate.min.js" charset="utf-8"></script>
</head>
<body ng-app="Signup">
Signup
<div ng-view></div>
<!-- <script type="text/javascript">
document.getElementById('showPswd').addEventListener("click", function() {
var pwd = document.getElementById("newPassword");
if (pwd.getAttribute("type") === "password") {
pwd.setAttribute("type", "text");
} else {
pwd.setAttribute("type", "password");
}
});
</script> -->
<script src="assets/js/signup.js" charset="utf-8"></script>
</body>
</html>
But only signup page is getting loaded.
I have checked my code with almost tutorial that I could find on routing and views on the front page of google, but nothing is working.
I am not receiving any error either.
Also, upon clicking on the link <a href="#/otp">Signup<a> my url changes to this http://127.0.0.1:36164/#!/signup#%2Fotp
I am having hard time to pass this error:
Uncaught Error: [$injector:modulerr]
when I am trying to make an authentication app with AngularJS. I put the code in plunker.
Here are my codes:
1- app.js
"use strict";
(function() {
var app = angular.module('loginApp', ['AuthService', 'Session']);
app.constant('appSettings', {
title:'Authentication Application',
version:'1.0'
});
app.constant('AUTH_EVENTS', {
loginSuccess: 'auth-login-success',
loginFailed: 'auth-login-failed',
logoutSuccess: 'auth-logout-success',
sessionTimeout: 'auth-session-timeout',
notAuthenticated: 'auth-not-authenticated',
notAuthorized: 'auth-not-authorized'
});
app.constant('USER_ROLES', {
all: '*',
admin: 'admin',
editor: 'editor',
guest: 'guest'
});
app.controller('footerController', function($scope, appSettings){
$scope.appSettings = appSettings;
});
}());
2 - applicationcontroller.js
"use strict";
(function() {
var applicationcontroller = function ($scope, USER_ROLES, AuthService) {
$scope.currentUser = null;
$scope.userRoles = USER_ROLES;
$scope.isAuthorized = AuthService.isAuthorized;
$scope.setCurrentUser = function (user) {
$scope.currentUser = user;
};
};
applicationcontroller.$inject = ['$scope', 'USER_ROLES', 'AuthService'];
angular.module('loginApp')
.controller('applicationcontroller', applicationcontroller);
}());
3- logincontroller.js
"use strict";
(function() {
var logincontroller = function ($scope, $rootScope, AUTH_EVENTS, AuthService) {
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function(credentials){
AuthService.login(credentials).then(function(user){
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
$scope.setCurrentUser(user);
}, function(error){
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
});
};
};
logincontroller.$inject = ['$scope', '$rootScope', 'AUTH_EVENTS', 'AuthService'];
angular.module('loginApp')
.controller('logincontroller', logincontroller);
}());
4- authservice.js
"use strict";
(function(){
var AuthService = function($http, Session){
var authService = {};
authService.login = function (credentials) {
return $http
.post('/login', credentials)
.then(function (res) {
Session.create(res.data.id, res.data.user.id,
res.data.user.role);
return res.data.user;
});
};
authService.isAuthenticated = function () {
return !!Session.userId;
};
authService.isAuthorized = function (authorizedRoles) {
if (!angular.isArray(authorizedRoles)) {
authorizedRoles = [authorizedRoles];
}
return (authService.isAuthenticated() &&
authorizedRoles.indexOf(Session.userRole) !== -1);
};
return authService;
};
AuthService.$inject = ['$http', 'Session'];
angular.module('loginApp').factory('AuthService', AuthService);
}());
5- session.js
"use strict";
(function(){
var Session = function(){
this.create = function (sessionId, userId, userRole) {
this.id = sessionId;
this.userId = userId;
this.userRole = userRole;
};
this.destroy = function () {
this.id = null;
this.userId = null;
this.userRole = null;
};
};
angular.module('loginApp').service('Session', Session);
}());
6- index.html
<!DOCTYPE html>
<html data-ng-app="loginApp" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Authentication</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link href="css/main.css" rel="stylesheet">
</head>
<body ng-controller="applicationcontroller">
<div class="container">
<div class="jumbotron">
<form name="loginForm" ng-controller="logincontroller" ng-submit="login(credentials)" novalidate>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" ng-model="credentials.username" class="form-control">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" ng-model="credentials.password" class="form-control">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<hr class="color-violet">
<footer class="text-center" data-ng-controller="footerController"> MADE WITH <i class="fa fa-heart color-violet"></i> BY <span class="color-violet">ALAN SABERI</span>. FIND THIS ON <span class="color-violet">GITHUB</span><div>Version: {{appSettings.version}}</div></footer>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="vendor/bootstrap.min.js"></script>
<script src="vendor/angular.min.js"></script>
<script arc="js/services/authservice.js"></script>
<script arc="js/services/session.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/applicationcontroller.js"></script>
<script src="js/controllers/logincontroller.js"></script>
</body>
</html>
First of all you have a typo when referencing your script files
<script arc="js/services/authservice.js"></script>
<script arc="js/services/session.js"></script>
Should be
<script src="js/services/authservice.js"></script>
<script src="js/services/session.js"></script>
Second -> Your AuthService and Session are not new modules, they are being registered in the same loginApp module based on your code. So you don't inject them into your loginApp module.
Change
var app = angular.module('loginApp', ['AuthService', 'Session']);
to this
var app = angular.module('loginApp', []);
Third -> You are loading your service script files before loading your app.js, remember app.js is where you are first defining your loginApp module that you are using to assign your services, so change your script load order to be this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap.min.js"></script>
<script src="angular.min.js"></script>
<script src="app.js"></script>
<script src="session.js"></script>
<script src="authservice.js"></script>
<script src="applicationcontroller.js"></script>
<script src="logincontroller.js"></script>
Here's your plnkr that's forked and working : http://plnkr.co/edit/5BEIsVxwt8sKwr4HA8Eq?p=preview
I'm trying to embed the dalliance genome browser into an Angular application.
It works fine when placed on the main page.
However, because the app is large, I am trying to use a Template-expanding directive.
I read some posts about inline javascript not playing well along Angular, and the solution. In particular I added this gist to my app.
My app now looks like this plunker.
Question: The genome browser plugin does not appear :-( What's wrong?
app.js:
(function(angular) {
'use strict';
angular.module('docsTemplateUrlDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.title = "Genome Browser";
}])
.directive('genomeBrowser', function() {
return {
templateUrl: 'genomeBrowser.html'
};
});
})(window.angular);
genomeBrowser.html:
<h2>Embedded page:</h2>
<script type='text/javascript-lazy' language="javascript">
new Browser(options);
</script>
<div id="svgHolder"></div>
(The options are not relevant here but can be seen in the plunker.)
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Genome browser</title>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script src="app.js"></script>
<script src="angular-loadscript.js"></script>
<script src="http://www.biodalliance.org/release-0.13/dalliance-compiled.js"></script>
</head>
<body ng-app="docsTemplateUrlDirective">
<div ng-controller="Controller">
<h1>{{title}}</h1>
<div genome-browser></div>
</div>
</body>
</html>
You forgot to include 'ngLoadScript' as a dependency:
angular.module('docsTemplateUrlDirective', [])
should be
angular.module('docsTemplateUrlDirective', ['ngLoadScript'])
Also, there was a missing quote in your partial in console.log('debug');
To solve this, I moved all inline javascript into the directive.
app.js:
(function() {
'use strict';
angular.module('app', []);
angular.module('app').controller('mainCtrl', ['$scope', function($scope) {
$scope.title = "Genome Browser";
}]);
angular.module('app').directive('genomeBrowser', function() {
return {
templateUrl: 'genomeBrowser.html',
restrict: 'E',
controller: function($scope) {
var browser = new Browser({
pageName: 'dalliance', // Target element ID.
chr: '22',
viewStart: 30000000,
viewEnd: 30030000,
cookieKey: 'human',
coordSystem: {
speciesName: 'Human',
taxon: 9606,
auth: 'NCBI',
version: '36',
ucscName: 'hg18'
},
sources: [{
name: 'Genome',
uri: 'http://www.derkholm.net:8080/das/hg18comp/',
tier_type: 'sequence',
provides_entrypoints: true
}, {
name: 'Genes',
desc: 'Gene structures from Ensembl 54',
uri: 'http://www.derkholm.net:8080/das/hsa_54_36p/',
collapseSuperGroups: true,
provides_karyotype: true,
provides_search: true
}, {
name: 'Repeats',
uri: 'http://www.derkholm.net:8080/das/hsa_54_36p/',
stylesheet_uri: 'http://www.derkholm.net/dalliance-test/stylesheets/ens-repeats.xml'
}, {
name: 'MeDIP raw',
uri: 'http://www.derkholm.net:8080/das/medipseq_reads'
}, {
name: 'MeDIP-seq',
uri: 'http://www.ebi.ac.uk/das-srv/genomicdas/das/batman_seq_SP/'
}]
});
}
};
});
})();
genomeBrowser.html:
<div id="dalliance"></div>
I still have things to learn about how to properly control this browser my for next homework, but this answers the question.
Plunk: http://plnkr.co/edit/KSUVq8?p=preview
I am learning angular.. I have tried to run a small example through pluralsight, but wasn't able to render correct output..
http://plnkr.co/edit/cYEDSW3FrAKeh1SBjUVN?p=preview
HTML
<!DOCTYPE html>
<html ng-app>
<head>
<script data-require="angular.js#*" data-semver="1.3.7" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{text}}</h1>
<div>
<div>First name: {{person.firstName}}</div>
<div>Last name: {{person.lastName}}</div>
<img ng-src="person.imageSrc" title="{{person.firstName}} {{person.lastName}}">
</div>
</body>
</html>
script.js
var MainController = function($scope) {
var person = {
firstName: "Ajay",
lastName: "Sattikar",
imageSrc: "http://odetocode.com/Images/scott_allen_2.jpg"
};
$scope.text = "Hello Angular!";
$scope.person = person;
};
I am not able to figure out why angular variables are getting displayed as normal text instead of its assigned value. Experts, kindly help...
There are a few things that need to be changed in your code
you need to create an angular module
var app = angular.module('app', []);
2 add directive to html element
<html ng-app='app'>
need to register MainController against angular module like this:
app.controller('MainController', function($scope) {
var person = {
firstName: "Ajay",
lastName: "Sattikar",
imageSrc: "http://odetocode.com/Images/scott_allen_2.jpg"
};
$scope.text = "Hello Angular!";
$scope.person = person;
});
Here is a working demo - http://plnkr.co/edit/i9N2OC75EGZwUTDcKtLB?p=preview
You missed a few steps:
1. Declaring your app
<html ng-app='myApp'>
2. Declaring your controller inside your app module:
angular.module('myApp', [])
.controller('MainController', function($scope) {
var person = {
firstName: "Ajay",
lastName: "Sattikar",
imageSrc: "http://odetocode.com/Images/scott_allen_2.jpg"
};
$scope.text = "Hello Angular!";
$scope.person = person;
})