I am learning AngularJs now a days and stuck in the error and couldn't resolve it for the last two days. First let's look at my code first:
MainPage.html
<!DOCTYPE html>
<html>
<head>
<title>Learn Angular Js - Scott Allen</title>
<meta charset="utf-8" />
</head>
<body ng-app="LearnAngular">
<h1>Git Hub Viwer</h1>
<div ng-view></div>
<script src="angular.js"></script>
<script src="angular-route.js"></script>
<script src="App.js"></script>
<script src="MainController.js"></script>
</body>
</html>
App.js
(function () {
var app = angular.module("LearnAngular", ["ngRoute"]);
app.config(function routeConfig($routeProvider) {
$routeProvider
.when("/main", {
templateUrl: function () {
debugger;
return "Main.html";
},
controller: "MainController"
})
.otherwise({ redirectTo: "/mian" });
});
}());
MainController.js
(function () {
var MainController = function ($scope, $interval, $location) {
alert("var MainController = function ($scope, $interval, $location) {};");
var decrementCountdown = function () {
$scope.countdown -= 1;
if ($scope.countdown < 1) {
$scope.search($scope.username);
}
};
var countDownPromise = null;
var startCountdown = function () {
countDownPromise = $interval(decrementCountdown, 1000, $scope.countdown);
};
$scope.search = function (username) {
if (countDownPromise) {
$interval.cancel(countDownPromise);
$scope.countdown = null;
}
// redirect to the url.
};
$scope.username = "angular";
$scope.countdown = 5;
startCountdown();
};
var app = angular.module("LearnAngular");
app.controller("MainController", MainController);
}());
Main.html
<div>
<h1>{{countdown}}</h1>
<form name="searchUser" ng-submit="search(username)">
<input type="search" required placeholder="Enter username to search" ng-model="username" />
<input type="submit" value="Search" />
</form>
</div>
When I run the application, i see this url:
http://localhost:52108/HomePage.html#/mian
which shows that I successfully redirect to the main route but Main.html is not being shown on the HomePage.html page and browser is not requesting for the Main.html when I examine the network of browser.
Here is the screen shot of my application:
I searched on the internet and tried many solutions but none of them solves my problem. I don't what is wrong with the code. I am developing in VisualStudio
Thanks in advance for your help and time.
You had typo in URL there in otherwise's redirectTo value, it should be /main
.otherwise({ redirectTo: "/main" });
Related
I have implemented a form with a particular controller and then after it is storing in a scope object and then after I assigned that scope object to a service property to share n number of controllers. After assignment the data to service property I am redirecting to another page where a form is their and it have some fields but I am unable to show the form in the web page.
Example: index.html:
<body ng-app="app" ng-controller="ctrl_1"> ... ..... </body>
main.js:
var app = angular.module("app",[]);
app.service("myService",function(){
this.Details = "";
this.setDetails = function(details){
this.Details = details;
};
this.getDetails = function(){
return this.Details;
} });
app.controller("ctrl_1",function($scope,myService){ after passing the data in service I redirect to index2.html window.location("index2.html"); });
app.controller("ctrl_2",function($scope,myService){ });
index2.html:
<body ng-app="app" controller="ctrl_2"> ..`enter code here` ....enter code here </body>
In this way I define, but I am unable to run the index2.html page.
You need a routing module such as ngRoute or ui.router. They will help you with redirection to other pages. Here is a quick demo for your scenario:
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "index.html"
})
.when("/page2", {
templateUrl: "index2.html"
});
});
app.service("myService", function() {
this.Details = "";
this.setDetails = function(details) {
this.Details = details;
};
this.getDetails = function() {
return this.Details;
}
});
app.controller("ctrl_1", function($scope, myService, $location) {
$scope.redirect = function(path) {
$location.url(path);
}
});
app.controller("ctrl_2", function($scope, myService, $location) {
$scope.redirect = function(path) {
$location.url(path);
}
});
<!DOCTYPE html>
<html ng-app="app">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular-route.js"></script>
<body>
<div ng-view></div>
<script type="text/ng-template" id="index.html">
<div ng-controller="ctrl_1">
Page 1 (index.html)
<br>
<button ng-click="redirect('/page2')">Redirect</button>
</div>
</script>
<script type="text/ng-template" id="index2.html">
<div ng-controller="ctrl_2">
Page 2 (index2.html)
<br>
<button ng-click="redirect('/')">Go back</button>
</div>
</script>
</body>
</html>
I get this error - Error: $controller:ctrlreg A controller with this name is not registered. All of my scripts are loaded, and I added them all in index.html.
All scripts are loaded
My controller:
(function() {
angular.module("nsoftModule").controller("nsoftController", ["nsoftService", function(nsoftService) {
var self = this;
self.service = nsoftService;
}])
})();
My directive:
(function() {
var weatherMod = angular.module("nsoftModule", []);
weatherMod.directive("nsoftDirective", function() {
return {
templateUrl: "Template/weatherTemplate.html",
controller: "nsoftController as nsoftCtrl"
}
});
})();
My service:
(function() {
var weatherMod = angular.module("nsoftModule", []);
weatherMod.service("nsoftService", ["http", function(http) {
var service = this;
}]);
})();
My module:
(function() {
var weatherMod = angular.module("nsoftModule", []);
})();
My template:
<div class="container">
<div ng-controller="nsoftController">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
</div>
</div>
My app.js:
(function() {
angular.module("nsoftApp", ["nsoftModule"]);
})();
And my index.html:
<!DOCTYPE html>
<html ng-app="nsoftApp">
<head>
<title>Nsoft App</title>
</head>
<body>
<nsoft-directive></nsoft-directive>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="weatherModule.js"></script>
<script src="Service/weatherService.js"></script>
<script src="Controller/weatherController.js"></script>
<script src="Directive/weatherDirective.js"></script>
<script src="app.js"></script>
</body>
</html>
just remove the global variable because in you are using anonymous self invoking function variable is only limited to one anonymous function. use like his
(function() {
angular.module("nsoftModule").controller("nsoftController", ["nsoftService", function(nsoftService) {
var self = this;
self.service = nsoftService;
}])
})();
(function() {
angular.module("nsoftModule").directive("nsoftDirective", function() {
return {
templateUrl: "Template/weatherTemplate.html",
controller: "nsoftController as nsoftCtrl"
}
});
})();
//change http to $http
(function() {
angular.module("nsoftModule").service("nsoftService", ["$http", function($http) {
var service = this;
}]);
})();
(function() {
angular.module("nsoftModule", []);
})();
since controller assign from the directive no need to declare it in the html also
<div class="container">
<div >
<p>Name : <input type="text" ng-model="nsoftCtrl.name"></p>
<h1>Hello {{nsoftCtrl.name}}</h1>
</div>
(function() {
angular.module("nsoftApp", ["nsoftModule"]);
})();
How to call ui-view from another Controller in AngularJS
This is my sample program. Actually in here I am using nested ui-view. The problem is when I click the submit
button initially it works fine and show an alert SampleController
But again i clicked it doesnt got to SampleController why?
I need to go to that controller when i click on submit button
Is it any error on my code.Please check it my stateProvider too.I am a new starter in AngularJS
Plese correct me Thank you...
var app=angular.module('TestApp', ['angular.filter','ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('category', {
views : {
"body" : {
url : '/category',
templateUrl : 'category.html',
controller : 'TestController'
}
}
})
.state('category.subcategory', {
url : '/subcategory',
views : {
"subbody#category" : {
templateUrl : 'sample.html',
controller : 'SampleController'
}
}
})
});
app.controller('MainController', MainController);
function MainController($scope,$state) {
alert("This is MainController")
$scope.getCategory=function(){
$state.go('category');
}
}
app.controller('TestController', TestController);
function TestController($scope, $state){
$scope.getData=function() {
alert("Call to Sample Controller")
$state.go('.subcategory');
}
}
app.controller('SampleController', SampleController);
function SampleController($scope,$state) {
alert("This is SampleController")
}
This is my sample HTML files
index.html
<!DOCTYPE html>
<html ng-app="TestApp">
<head>
<link rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.js"></script>
<script src="angular-ui-router.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
Click to Category
<div ui-view="body">
<div ui-view="subbody"></div>
</div>
</body>
</html>
category.html
<div>
<input type="button" name="button" id="button" value="Submit" ng-click="getData()" />
<div ui-view="subbody"></div>
</div>
sample.html
<div>
Sample Controller
</div>
I need to hit SampleController when i click submit button
this.$state.go(".subcategory", null, { reload : true });
I think you should define one service and inject into controller. Then there is a chance to work.
Controller:
app.controller('TestController', TestController);
function TestController($scope, mainService) {
$scope.getData = function() {
mainService.getDetails();
//$state.go(.subcategory) //you can use here,If fails I have written in service(inject $state)
};
}
Service:
app.service('mainService', mainService)
mainService.$inject = ['$http', '$state'];
function mainService($http, $state) {
this.getDetails = function() {
console.log("Hai");
$state.go(.subcategory);
}
}
I'm able to my buttons work. The only is that I can't get them to work with AngluarJS. This is what happens: When I click the link to enter the page to where my facebook buttons are located, they don't show the first time. They only show up every time I click the refresh button at the top. How can I make it work so that they always show up right when I click the link to the page? My facebook div content code is under third.html which I labeled as FB Test on the app website. My script code for facebook is on my index.html page which is also where I set up my angular to link and label each page. Plus, please use a local host to test the app website. Here's my code:
index.html has...
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/master.css">
<script src= "js/angular.min.js"></script>
<script src= "js/angular-route.min.js"></script>
<script src= "js/jquery-2.1.3.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<link href="js/angular.min.js.map"></link>
<link href="js/angular-route.min.js.map"></link>
<script>
var pattern = /http:.+?(?=.jpg)(....)/;
var pieces = [];
var data = $.ajax({
dataType: "json",
url: "js/data.json",
success: function(){
$.each(data.responseJSON,function(){
//todo: add a placeholder image if there wasnt a url
if(this.piece_image != ""){
this.image_URL = /http:.+?(?=.jpg)(....)/.exec(this.piece_image)[0];
}
pieces.push(this);
})
data.destroy;
}
});
</script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<!--style effects comment box position-->
<style>
.fb-comments, .fb-comments iframe[style], .fb-like-box, .fb-like-box iframe[style] {
width: 100% !important;
}
.fb-comments span, .fb-comments iframe span[style], .fb-like-box span, .fb-like-box iframe span[style] {
width: 100% !important;
}
</style>
</head>
<body ng-app="app" style="padding-top:20px;">
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
//*This is where our app id must go
//Note to myself:
//the following number was created from my test app called "Davidow Project test" which is currently not live
//login to facebook, go to https://developers.facebook.com/apps/ to see test app
appId : '435225213325487',
channelUrl : '//localhost:8080/#/second',
status : true,
xfbml : true,
version : 'v2.1'
});
};
</script>
<script>
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}
(document, 'script', 'facebook-jssdk'));
</script>
<div class="container">
Home |
Explore |
Gallery |
Map |
Tile View |
FB Test
<div ng-view></div>
<!--TWITTER-->
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
</div>
</body>
</html>
**third.html has...**
<!--FACEBOOK CONTENT-->
<!--*must replace data-href with url of app site-->
<!--like button and share buttons-->
<div class="fb-like" data-href="http://www.example.com/" data-layout="standard" data-action="like" data-show-faces="true" data-share="true"></div>
<!--comment section-->
<!--added in a data-width number to resize comment box-->
<div class="fb-comments" data-href="http://www.example.com/" data-numposts="3" data-width="350px;" data-colorscheme="light"
data-layout="standard"></div>
<!--TWITTER-->
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
Tweet
**app.js has...**
var app = angular.module("app", ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: './views/main.html',
controller: 'mainController'
})
.when('/explore', {
templateUrl: './views/explore.html',
controller: 'mainController'
})
.when('/gallery', {
templateUrl: './views/gallery.html',
controller: 'gallery'
})
.when('/map', {
templateUrl: './views/map.html',
controller: 'mainController'
})
.when('/tileView', {
templateUrl: './views/tileView.html',
controller: 'tileView'
})
.when('/fbtest', {
templateUrl: './views/third.html',
controller: 'mainController'
})
});
app.controller('mainController', ['$scope', '$location', '$log', function($scope, $location, $log){
}]);
app.controller('gallery', ['$scope', '$location', '$log', function($scope, $location, $log){
$scope.pieces = pieces;
}]);
app.controller('tileView', ['$scope', '$location', '$log', function($scope, $location, $log){
window.scope = $scope;
$scope.pieces = pieces;
$scope.url = [];
for(var i = 0; i < pieces.length; i++){
$scope.url.push(pieces[i].image_URL);
}
}]);
You are loading the Social Plugins asynchronously, so you need to use FB.XFMBL.parse after loading them:
FB.XFBML.parse();
Source: https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse
I found a basic example on youtube that demonstrates routes through angular. When I load the set of files from this screen http://www.youtube.com/watch?v=zogrnQjHZAM it does not work.
I can see the index.html, but the partials do not render. I think it is because I am not serving these files through a server. If that is the case, how is angular different? I thought static files can be seen without them being served.
index.html -
<!doctype html>
<html ng-app="website">
<head>
<title>AngularJS Website</title>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/website.css">
</head>
<body>
<!-- top -->
<header id="header">
<h1 id="logo"></h1>
<div id="menu">
Home
About
Experiments
</div>
<div class="color"></div>
<div class="clear"></div>
</header>
<!-- //top -->
<div class="shadow"></div>
<div id="container">
<div ng-view></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script type="text/javascript" src="js/website.js"></script>
</body>
</html>
Router --
angular.module('website', []).
config(function ($routeProvider) {
$routeProvider.
when('/about', {templateUrl: 'partials/about.html', controller: 'AboutCtrl'}).
when('/experiments', {templateUrl: 'partials/experiments.html', controller: 'ExperimentsCtrl'}).
when('/home', {templateUrl: 'partials/home.html', controller: 'HomeCtrl'}).
otherwise({redirectTo: '/home'});
})
.controller('AboutCtrl', ['$scope', 'StateService', function ($scope, StateService) {
$scope.title = 'About Page';
$scope.body = 'This is the about page body';
$scope.message = StateService.getMessage();
$scope.updateMessage = function (m) {
StateService.setMessage(m);
};
}])
.controller('ExperimentsCtrl', ['$scope', 'StateService', function ($scope, StateService) {
$scope.title = 'Experiments Page';
$scope.body = 'This is the about experiments body';
$scope.message = StateService.getMessage();
$scope.updateMessage = function (m) {
StateService.setMessage(m);
};
}])
.controller('HomeCtrl', ['$scope', 'StateService', function ($scope, StateService) {
$scope.title = 'Home Page';
$scope.body = 'This is the about home body';
$scope.message = StateService.getMessage();
$scope.updateMessage = function (m) {
StateService.setMessage(m);
};
}])
.factory('StateService', function () {
var message = 'Hello Message';
var getMessage = function() {
return message;
};
var setMessage = function(m) {
message = m;
};
return {
getMessage: getMessage,
setMessage: setMessage
}
});
Your forgot to add ngRoute module in your module:
angular.module('website', [ngRoute]).
config(function ($routeProvider) ...
You also have to include the angular-route js file. Which is not bundled with angularjs now..
and this will work