angular ng-click on list item not firing - angularjs

Still learning angular, I would like to tap on an item from a list and show alert with the name of the item that was tapped.
In mainMenu.html ng-click is registered with the list element ng-click="mainMenuSelection(item.name), but the alert(name) is not being called in controllers.js
What am I doing wrong? Thanks
I also noticed the Google Chrome Sources does not show the views folder which contains mainMenu.html as per the second image.
//---app.js-----------------------------------------------
(function () {
'use strict';
angular
.module('angApp', ['ngRoute'])
.config(['$routeProvider', routeProvider]);
})();
function routeProvider ($routeProvider) {
$routeProvider.when('/list', {
templateUrl: 'views/mainMenu.html',
controller: 'MainMenuCtrl'
}).otherwise({ //home page
redirectTo: '/list'
});
}
angular.element(document).ready(function () {
angular.bootstrap(document, ['angApp']);
});
//---controllers.js-----------------------------------------------
angular
.module('angApp')
.controller('MainMenuCtrl', ['$scope', '$http', MainMenuCtrl]);
function MainMenuCtrl ($scope, $http) {
$http.get('js/mainMenu.json').then(
function (response) {
$scope.menuItems = response.data;
},
function (error) {
alert("http error");
}
)
$scope.mainMenuSelection = function(item) {
alert(item);
}
}
//---headerCtrl.js-----------------------------------------------
angular
.module('angApp')
.controller('HeaderCtrl', ['$scope', HeaderCtrl]);
function HeaderCtrl() {
var vm = this;
vm.title = "Tap left menu \u2630";
vm.headerTitle = setHeaderTitle;
function setHeaderTitle(title) {
vm.title = title;
}
}
//---index.html-----------------------------------------------
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/index.css">
<base href="http://localhost:63342/an1/">
<script src="angular.js"></script>
<script src="angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/controllers.js"></script>
<script src="js/controllers/headerCtrl.js"></script>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<main ng-view></main>
</body>
</html>
//---mainMenu.html-----------------------------------------------
<section class="mainMenu">
<ul>
<li ng-repeat="item in menuItems" ng-click="mainMenuSelection(item.name)">
<image src="images/{{item.image}}.png"></image>
{{item.name}}
</li>
</ul>
</section>

I created a fiddle with a working example close to what you want.
Obviously, I have a much pared down version for the sake of brevity.
http://jsfiddle.net/frishi/U3pVM/21624/
(function () {
'use strict';
angular
.module('angApp', [])
.controller("MainMenuCtrl", MainMenuCtrl)
})();
function MainMenuCtrl ($scope, $http) {
$scope.menuItems = [{
name:"Tom"},
{name: "Harry"},
{name: "Wiley"}
]
$scope.mainMenuSelection = function(item) {
alert(item);
}
}
Markup:
<div ng-app="angApp">
<section class="mainMenu" ng-controller="MainMenuCtrl">
<ul>
<li ng-repeat="item in menuItems" ng-click="mainMenuSelection(item.name)">
<image src="images/{{item.image}}.png" />
{{item.name}}
</li>
</ul>
</section>
</div>
I used a hard-coded JSON array of objects.
I also don't bootstrap the app the way you do.
There is too little information that your question provides, as to what could be the fault. Follow the example as specified in the fiddle, and if that doesn't work, reply with more details.

Here is my version in Plunker. I was trying to follow your file structure.
Make sure that <body ng-app="angApp"> is there, thats only one thing that I've added (I now it looks too trivial...)
EDIT: adding Git repo
Git repo with working code => clone => cd to directory => npm instal = npm start => files will be served on port:63342 (serving file using node sever in order to replicate environment where issue is happening)

Related

Angular loading Controllers and Services

I am using Angularjs for my application.I am having one common page which has header and footer which i am making common for all pages.Thats y i am placing it in one common html.Only contents code i am placing in other html pages.
As i am using one common page i am loading all controllers and all Services that i am using in the application.
Here is my commonpage.html
<!DOCTYPE html>
<html lang="en" data-ng-app="adminApp">
<head>
</head>
<body>
<!--Here is header code-->
<div class="LeftMenu">
<ul class="navbar">
<a href="#!/admindashboardhome" title="Dashboard"><li>
<span>Dashboard</span></li>
</a>
<a href="#!/examinationhalltickets" title="Declaration"><li>
<span>Examination Form</span></li>
</a>
<a href="#!/collegedetails" title="Declaration"><li>College
Details</li>
</a>
</ul>
</div>
<!--followed by footer code-->
<div data-ng-view> <!--ng-view-->
</div>
<!--Here i am loading all controllers and services related to application-->
<script
src="resources/angular/controller/admin/AdminExamController.js">
</script>
<script src="resources/angular/service/admin/AdminExamService.js">
</script>
<!-- And many more in same fashion-->
</body>
</html>
The doubt i am having is,is it necessary to place all controllers and services like i am doing because i am facing performance issue even though i am connected to strong internet it loads very slow.As i am placing all in one page it is loading all controllers and services everytime.If i place controllers in their respective html then i am getting error like ExamController.js or any .js Controller not defined.Is there any other way that i can load all controllers and services so that i can increase the performance of the application?
I think this is what your looking for
app.js
/* Module Creation */
var app = angular.module ('adminApp', ['ngRoute']);
app.config(['$routeProvider', '$controllerProvider', function($routeProvider, $controllerProvider){
/*Creating a more synthesized form of service of $ controllerProvider.register*/
app.registerCtrl = $controllerProvider.register;
function loadScript(path) {
var result = $.Deferred(),
script = document.createElement("script");
script.async = "async";
script.type = "text/javascript";
script.src = path;
script.onload = script.onreadystatechange = function (_, isAbort) {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
if (isAbort)
result.reject();
else
result.resolve();
}
};
script.onerror = function () { result.reject(); };
document.querySelector("head").appendChild(script);
return result.promise();
}
function loader(arrayName){
return {
load: function($q){
var deferred = $q.defer(),
map = arrayName.map(function(name) {
return loadScript(name+".js");
});
$q.all(map).then(function(r){
deferred.resolve();
});
return deferred.promise;
}
};
}
$routeProvider
.when('/view2', {
templateUrl: 'view2.html',
resolve: loader(['Controller2'])
})
.when('/bar',{
templateUrl: 'view1.html',
resolve: loader(['Controller1'])
})
.otherwise({
redirectTo: document.location.pathname
});
}]);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.min.js"></script>
</head>
<body ng-app="adminApp">
<!--Here is header code-->
<div class="LeftMenu">
<ul class="navbar">
<a href="#!/admindashboardhome" title="Dashboard"><li>
<span>Dashboard</span></li>
</a>
<a href="#!/examinationhalltickets" title="Declaration"><li>
<span>Examination Form</span></li>
</a>
<a href="#!/collegedetails" title="Declaration"><li>College
Details</li>
</a>
</ul>
</div>
<!--followed by footer code-->
<div data-ng-view> <!--ng-view-->
</div>
<!--Here i am loading all controllers and services related to application-->
<script
src="app.js">
</script>
<!-- And many more in same fashion-->
</body>
</html>
Controller 1.js
(function(val){
'use strict';
angular.module('Controller1App', [])
.controller('Controller1', ['$http','$rootScope','$scope','$window', function($http,$rootScope, $scope, $window){
//Your code goes here
}])
})(this);
Controller 2.js
(function(val){
'use strict';
angular.module('Controller2App', [])
.controller('Controller2', ['$http','$rootScope','$scope','$window', function($http,$rootScope, $scope, $window){
//Your code goes here
}])
})(this);
Refer https://plnkr.co/edit/cgkgG5PCwJBVOhQ1KDW2?p=preview

Why do I keep getting the $[injector:modulerr] uncaught error when all dependencies have been injected?

Below is my index.html page which has two buttons which links to 2 different views which i intend to show using angular routing.
Below is my
HTML
<!DOCTYPE html>
<html>
<head>
<title>PR_APP</title>
<link rel="stylesheet" href="css/style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-route.js"></script>
<script src="js/main.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="new_pr_app">
<h2>Please select an option</h2><br>
<div ng-controller="view_controller">
<button id="view_details" ng-click="view()">View Details</button>
</div>
<div ng-controller="update_controller">
<button id="update_details" ng-click="update()">Update Details</button>
</div>
<div ng-view>
</div>
</body>
Below is my main.js file which houses both above mentioned controller and logic for angular routing.
main.js
var app = angular.module('new_pr_app', ['ngRoute']);
app.config('$routeProvider','$locationProvider', function($routeProvider,$locationProvider){
$routeProvider.when("/update",
{
templateUrl:"update.html",
controller: "update_controller"
})
.when("/view",
{
templateUrl: "view.html",
controller: "view_controller"
});
});
app.controller("view_controller",function($scope, $location, http_factory){
$scope.view = function(){
$location.path("/view");
}
$scope.result =[];
http_factory.get_request().then(function(response){
$scope.result = response.data;
});
});
app.controller("update_controller",function($scope, $location, http_factory){
$scope.update_details = function(){
$location.path("/update");
}
$scope.names = [];
http_factory.get_request().then(function(response){
$scope.names = response.data;
});
});
I have another file called services.js which has a service factory to get details from a json file using an http get.
My only problem seems to be in the above main.js which gives the error below everytime index.html loads
angular.js:88 Uncaught Error: [$injector:modulerr]
Your config is wrong. You pass in a string as the first (and second argument), while the .config(..) function, expects a function to be passed in (or an array).
In your code, you simply forgot to wrap the arguments in an array. Here's how it should look:
app.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider){
$routeProvider.when("/update",
{
templateUrl:"update.html",
controller: "update_controller"
})
.when("/view",
{
templateUrl: "view.html",
controller: "view_controller"
});
}]);
Note the [ and ] wrapping the content
You can check with below code.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-route.js"></script>
<body ng-app="new_pr_app">
<h2>Please select an option</h2><br>
<div ng-controller="view_controller">
<button id="view_details" ng-click="view()">View Details</button>
</div>
<div ng-controller="update_controller">
<button id="update_details" ng-click="update_details()">Update Details</button>
</div>
<div ng-view>
</div>
<script>
var app = angular.module('new_pr_app', ['ngRoute']);
app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider){
$routeProvider.when("/update",
{
template:"update template"
// controller: "update_controller"
})
.when("/view",
{
template: "view template"
// controller: "view_controller"
});
}]);
app.controller("view_controller",function($scope, $location){
$scope.view = function(){
$location.path("/view");
}
});
app.controller("update_controller",function($scope, $location){
$scope.update_details = function(){
$location.path("/update");
}
});
</script>
</body>
</html>

Unable to display content using angular ui

simple angular ui example not working. There are no errors in console.
Here is the example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
</head>
<script>
window.onload = function ()
{
var myApp = angular.module('myApp', ['ui.router']);
myApp.controller('MainCtrl', function ($scope) {
});
myApp.config(function ($stateProvider, $urlRouterProvider) {
// default route
$urlRouterProvider.otherwise("/first");
// ui router states
$stateProvider
.state('first', {
url: "/first",
views: {
header: {
template: '<h1>First header</h1>',
controller: function ($scope) {
}
},
content: {
template: '<p>First content</>',
controller: function ($scope) {
}
},
footer: {
template: '<div>First footer</div>',
controller: function ($scope) {
}
}
}
});
});
}
</script>
<body ng-controller="MainCtrl">
<ul>
<li>First</li>
<li>Second</li>
</ul>
<div ui-view="header"></div>
<div ui-view="content"></div>
<div ui-view="footer"></div>
<!-- Bootstrap core JavaScript + Angular Js
================================================== -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui/0.4.0/angular-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
</body>
</html>
I have included all the resources using external cdn. The template content written in angular is not displayed. I am I doing it correctly?
Here is the plunker: Plunker
You have not mentioned app name anywhere in the view.
<html lang="en" ng-app="myApp">
Here is the working Plunker
Remove window.onload. Make sure the angular and ui-router scripts are loaded before your script. And add the missing ng-app="myApp" to the html element.
Plunkr: http://plnkr.co/edit/XaR3KD2hJ1jOVZ2mWi5H?p=preview

Show parts of the page with ng-show like virginamerica website

in my project i've to do something very similar to virginamerica.com ux logic.
I've to set my page in 3 parts, and set them visible depending on the routeParams. So, imagine this:
A list of items [visible on the root]
Detail of the item with some variations [visible on the root/item]
Item editor page [visible on the root/item/var]
I'm trying to set up an angular application to do this, but i've some problems, i'm doing something like this:
in my index.html i've this code:
<!DOCTYPE html>
<html ng-app="box">
<head lang="en">
<meta charset="utf-8">
<title>Box loader</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="box.js"></script>
<!-- <base href="/"> -->
</head>
<body ng-controller="boxCtrl">
<section id="box-chooser">
<ul>
<li ng-repeat="box in boxes">
{{box.boxname}}
</li>
</ul>
</section>
<div ng-show="detailVisible">
<section ng-controller="boxDetailCtrl">
<h1>detail {{boxcode}}</h1>
</section>
</div>
</body>
</html>
this is the angularjs part:
var app = angular.module('box', []);
app.config(function($routeProvider /*$locationProvider*/) {
$routeProvider
.when('/', {} )
.when('/:boxid', {
})
//$locationProvider.html5Mode(true);
});
app.controller('boxCtrl', function($scope, $route, $location) {
$scope.$on('$routeChangeSuccess', function() {
var path = $location.path();
console.log(path);
$scope.detailVisible = false;
if(path === '/123') {
$scope.detailVisible= true;
}
});
$scope.boxes = [{'boxid':'123', 'boxname': 'name1'}, {'boxid':'189', 'boxname': 'name2'}, {'boxid':'156', 'boxname': 'name3'}]
});
app.controller('boxDetailCtrl', function($scope, $route, $location){
$scope.boxcode = $location.path();
console.log('secondo:' + $location.path())
});
Problem is that boxcode on the second controller works only after a page refresh on localhost/#/123 and ng-show works on the path change.
Any better idea to doing this?
Thanks in advance :)

Cant integrate facebook login to angular app using ngFacebook

Somehow I am not able to integrate facebook Login to my angularjs app, though I feel I am just loosing a minor mistake which I cant point out and thus you geeks might be sureshot help!
I have used this plunker example:
Following the above code same as what has been mentioned in plunker, below are y files.
my app.js {which has nothing but routing info, ngFacebook module I have injected in controller.js}
'use strict';
// Declare app level module which depends on filters, and services
angular.module('ngdemo', ['ngdemo.filters', '$strap.directives', 'ngdemo.services', 'ngdemo.directives', 'ngdemo.controllers']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/view5', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl4'});
$routeProvider.when('/view1', {templateUrl: 'modulepages/home.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
$routeProvider.when('/view4', {templateUrl: 'modulepages/bizregistration.html', controller: 'MyCtrl3'});
$routeProvider.when('/view6', {templateUrl: 'partials/modalcontent.html', controller: 'MyCtrl5'});
$routeProvider.otherwise({redirectTo: '/view5'});
}]);
And this is my Controller.js which has the heart of ngFacebook Integration.
'use strict';
/* Controllers */
var app = angular.module('ngdemo.controllers', ['ngResource', 'ngFacebook'])
.config([ '$facebookProvider', function( $facebookProvider ) {
alert("am i here?");
$facebookProvider.setAppId('239661002870669');
}]);
// Clear browser cache (in development mode)
//
// http://stackoverflow.com/questions/14718826/angularjs-disable-partial-caching-on-dev-machine
app.run(function ($rootScope, $templateCache) {
(function(){
// If we've already installed the SDK, we're done
if (document.getElementById('facebook-jssdk')) {return;}
// Get the first script element, which we'll use to find the parent node
var firstScriptElement = document.getElementsByTagName('script')[0];
// Create a new script element and set its id
var facebookJS = document.createElement('script');
facebookJS.id = 'facebook-jssdk';
// Set the new script's source to the source of the Facebook JS SDK
facebookJS.src = '//connect.facebook.net/en_US/all.js';
// Insert the Facebook JS SDK into the DOM
firstScriptElement.parentNode.insertBefore(facebookJS, firstScriptElement);
}());
$rootScope.$on('$viewContentLoaded', function () {
$templateCache.removeAll();
});
});
app.controller('DemoCtrl', ['$scope', '$facebook', function ($scope, $facebook) {
alert("I am here out");
$scope.isLoggedIn = false;
$scope.login = function() {
$facebook.login().then(function() {
refresh();
});
}
function refresh() {
$facebook.api("/me").then(
function(response) {
$scope.welcomeMsg = "Welcome " + response.name;
$scope.isLoggedIn = true;
},
function(err) {
$scope.welcomeMsg = "Please log in";
});
}
refresh();
}]);
and that's my index.html
<!DOCTYPE html>
<html ng-app="ngdemo" lang="en">
<head>
<meta charset="utf-8">
<title>You local needs are just a pingle away - pingle.com</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/app.css"/>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body ng-controller="DemoCtrl" bgcolor="#e8e8e8">
<div class="container">
<h4>
{{welcomeMsg}}
</h4>
<button type="button" ng-click="login()" ng-hide="isLoggedIn" class="btn btn-default navbar-btn">
Login
</button>
</div>
<div id="fb-root">
</div>
<div ng-view>
</div>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="lib/angular/angular-strap.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.7.0.js">
</script>
<script src="//rawgithub.com/GoDisco/ngFacebook/master/ngFacebook.js"></script>
</body>
</html>
Could you please help where the problem is, it will be a great help and it is the important part of my application.
I just copied/pasted your code in my IDE and tested it.
I had to remove some things to simplify the testing.
E.g. remove filters, directives, services and also the config for the routeprovider.
I also removed angular-strap. I updated the facebook app id to an ID of an app I own...
If you remove everything you can get it working, then you can gradually add what you need, like routing, angular-strap etc. maybe one of those creates problems...
The code you provided (cleaned with all unnecessary stuff) just worked fine for the facebook login, like the plunker code...
At the moment of writing, if you do not specify the API Facebook version you may get an error in the console, thus I specify it like this:
angular.module('app')
.config(function ($facebookProvider) {
$facebookProvider.setAppId(facebookAppId);
$facebookProvider.setCustomInit({
version: 'v2.1'
});
$facebookProvider.setPermissions('email');
});
Actually I think this question can be closed because the code provided was incomplete and needed some effort, like removing all the unneded stuff as I mentioned...

Resources