ng-view not show with Route (angularjs) - javascript

I'm doing the tutorial about angularjs. Everything is fine until working with route.
I 'm search about this problem before, but it not working for me.
I'm doing exactly the code which author type but it's not working.
ng-view put in index.html
<html ng-app="githubViewer">
<head>
<title>Demo</title>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/angular-route.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="MainController.js"></script>
<script type="text/javascript" src="github.js"></script>
</head>
<body>
<h1>Github Viewer</h1>
<div ng-view=""></div>
</body>
app.js
(function() {
var app = angular.module("githubViewer", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({redirectTo:"/main"});
});})();
MainController.js
(function() {
var app = angular.module("githubViewer");
var MainController = function(
$scope, $interval, $location) {
var decrementCountdown = function() {
$scope.countdown -= 1;
if ($scope.countdown < 1) {
$scope.search($scope.username);
}
};
var countdownInterval = null;
var startCountdown = function() {
countdownInterval = $interval(decrementCountdown, 1000, 5, $scope.countdown);
};
$scope.search = function(username) {
if (countdownInterval) {
$interval.cancel(countdownInterval);
$scope.countdown = null;
}
};
$scope.username = "angular";
$scope.countdown = 5;
startCountdown();
};
app.controller("MainController", MainController);})();
main.html
<div>
{{countdown}}
{{username}}
<form name="searchUser" ng-submit="search(username)">
<input type="search" required placeholder="usẻname to ind" ng-model="username" />
<input type="submit" value="Search" ng-click="search(username)">
</form>
github.js
(function() {
var github = function($http) {
var getUser = function(username){
return $http.get("https://api.github.com/users/" + username)
.then(function(response){
return response.data;
});
};
var getRepos = function(user){
return $http.get(user.repos_url)
.then(function(response){
return response.data;
});
};
return{
getUser : getUser,
getRepos: getRepos
};
};
var module = angular.module("githubViewer");
module.factory("github", github);})();

You have an error in your code:
var MainController = function($scope, $interval, , $location) {
// unnecessary comma here ----^
Remove comma (or insert missing parameter) and your app should start working.
In general I recommend to keep developer console open all the time during coding.

Related

Pluralsight - AngularJS: Get Started

I follow the "AngularJS: Get Started" course from Plualsight, and I reach the Routing module, so I have some files in Plunker, on the course they can see on Preview page the title which is "Github Viewer" and a search bar. But I still get errors in console, and I do not know why, my code should be identical as their code.
So I have the following files :
app.js
(function() {
var app = angular.module('githubViewer', ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({redirectTo: "/main"});
});
}());
github.js
(function() {
var github = function($http) {
var getUser = function(username) {
return $http.get("https://api.github.com/users/" + username)
.then(function(response) {
return response.data;
});
};
var getRepo = function(user) {
return $http.get(user.repos_url)
.then(function(response) {
return response.data;
});
};
return {
getUser : getUser,
getRepo : getRepo
};
};
var module = angular.module("githubViewer");
module.factory("github", github);
}());
index.html
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script data-require="angular.js#*" data-semver="1.3.14" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script data-require="angular-route#*" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script scr="app.js"></script>
<script src="MainController.js"></script>
<script src="github.js"></script>
</head>
<body>
<h1>Github Viewer</h1>
<div ng-view></div>
</body>
</html>
main.html
<div>
{{ countdown }}
<form name="searchUser" ng-submit="search(username)">
<input type="search" required="" ng-model="username" />
<input type="submit" value="Search" />
</form>
</div>
MainController.js
// Code goes here
(function() {
var app = angular.module("githubViewer");
var MainController = function($scope, $interval, $location) {
console.log("Atentie!")
var decrementCountdown = function() {
$scope.countdown -= 1;
if ($scope.countdown < 1) {
$scope.search($scope.username);
}
};
var countdownInterval = null;
var startCountdown = function() {
countdownInterval = $interval(decrementCountdown, 1000, $scope.countdown);
};
$scope.search = function(username) {
if (countdownInterval) {
$interval.cancel(countdownInterval);
$scope.countdown = null;
}
//
};
$scope.username = "Angular";
$scope.countdown = 5;
startCountdown();
};
app.controller("MainController", MainController);
}());
userdetails.html
<div id="userDetails">
<h2>{{user.name}}</h2>
<img ng-src="{{user.avatar_url}}" title="{{user.name}}">
<div>
Order:
</div>
<select ng-model="repoSortOrder">
<option value="+name">Name</option>
<option value="-stargazers_count">Stars</option>
<option value="+language">Language</option>
</select>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Stars</th>
<th>Language</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos | limitTo:10 | orderBy:repoSortOrder">
<td>{{repo.name}}</td>
<td>{{repo.stargazers_count | number }}</td>
<td>{{repo.language}}</td>
</tr>
</tbody>
</table>
And the style.css which is empty.
So at this point I should see in a separete window something like in the following picture and no errors in console.
But I se only the title, like in the following picture
and errors
Could someone help me to understand why isnt' work ?
Was some changes in AngularJS and the course isn't up to date ?
You made a typo
<script scr="app.js"></script>
should be
<script src="app.js"></script>
Also make sure that when using angularjs core api's, all the API should be off same version. Here you're using angularjs (ver. 1.3.12) & angular-route (ver. 1.6.2)
Change both to 1.6.2 or latest
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-route.js"></script>
Demo Here

No Inheritance is occuring in the angularJS code

This is an AngularJS inheritance code where the inheritance is applied in the functions but there is no output coming for this code.
custDetails and empPaycheck are the two functions where inheritance is applied but the code has some error which I am not been able to find.
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Controller Inheritance</title>
<script src="angulaar.min.js"></script>
<script>
var app = angular.module("sample",
[]).run(["$rootScope",function($rootScope){
$rootScope.taxPe`enter code here`rcent = 30;
}]);
app.controller("custDetails", ["$scope",function($scope) {
$scope.Name = "Dipanshu";
$scope.Sal = 45000;
$scope.Dept = "Testing";
}]);
app.controller("empPayCheck", ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.getTaxes = function() {
return $scope.Sal * $rootScope.taxPercent / 100;
};
$scope.getNet = function() {
return $scope.Sal - $scope.getTaxes();
};
}]);
</script>
</head>
<body ng-app="sample">
<div ng-controller="custDetails">
Employee Details of {{Name}}
<div ng-controller="custDetails">
{{Name}} earns {{Sal}} rs and is in <strong>{{Dept}}</strong>
Department.
<div controller="empPayCheck">
Tax: {{getTaxes()}}
<br> Net Amount: {{getNet()}}
</div>
</div>
</div>
</body>
</html>
You should use $scope.$parent to access parent $scope variables in a child controller.
Also in your HTML code there's a typo where controller should be ng-controller.
Look at the following working example.
var app = angular.module("sample", []).run(["$rootScope", function($rootScope) {
$rootScope.taxPercent = 30;
}]);
app.controller("custDetails", ["$scope", function($scope) {
$scope.Name = "Dipanshu";
$scope.Sal = 45000;
$scope.Dept = "Testing";
}]);
app.controller("empPayCheck", ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.getTaxes = function() {
return $scope.$parent.Sal * $rootScope.taxPercent / 100;
};
$scope.getNet = function() {
return $scope.$parent.Sal - $scope.getTaxes();
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="sample">
<div ng-controller="custDetails">
Employee Details of {{Name}}
<div>
{{Name}} earns {{Sal}} rs and is in <strong>{{Dept}}</strong> Department.
<div ng-controller="empPayCheck">
Tax: {{getTaxes()}}
<br> Net Amount: {{getNet()}}
</div>
</div>
</div>
</body>
There is error in your module run block near $rootScope.taxPe;
You are using controller attribute instead of ng-controller.
Here is a working code snippet:
var app = angular.module("sample", []).run(["$rootScope", function($rootScope) {
$rootScope.taxPercent = 30;
}]);
app.controller("custDetails", ["$scope", function($scope) {
$scope.Name = "Dipanshu";
$scope.Sal = 45000;
$scope.Dept = "Testing";
}]);
app.controller("empPayCheck", ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.getTaxes = function() {
return $scope.Sal * $rootScope.taxPercent / 100;
};
$scope.getNet = function() {
return $scope.Sal - $scope.getTaxes();
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="sample">
<div ng-controller="custDetails">
Employee Details of {{Name}}
<div ng-controller="custDetails">
{{Name}} earns {{Sal}} rs and is in <strong>{{Dept}}</strong> Department.
<div ng-controller="empPayCheck">
Tax: {{getTaxes()}}
<br> Net Amount: {{getNet()}}
</div>
</div>
</div>
</body>
P.S.: Personally I would not recommend using $rootScope and scope inheritance, you can use services to share data between controllers. Also would suggest you looking into component API that comes in v1.5+.

How to change the innerHTML content onmouseout in angular

I have to change the content of the button to ON on mouseenter and to OFF on mouseleave using Angular.
<html ng-app="myApp" ng-controller="homeCtrl">
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('homeCtrl', function ($scope) {
$scope.alert = function () {
this.myHTML = OFF;
};
$scope.text = function () {
this.myHTML = ON;
};
})
</script>
</head>
<body>
<button ng-mouseenter="alert();" ng-mouseleave="text();"> OFF </button>
</body>
</html>
$scope.alert = function () {
$scope.text = 'OFF';
};
$scope.text = function () {
$scope.text = 'ON';
};
and
<button ng-mouseenter="alert();" ng-mouseleave="text();">{{text}}</button>
Why not use binding instead?
<html ng-app="myApp" ng-controller="homeCtrl">
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('homeCtrl', function ($scope) {
$scope.alert = function () {
$scope.value = "OFF";
};
$scope.text = function () {
$scope.value = "ON";
};
$scope.value="OFF"
})
</script>
</head>
<body>
<button ng-mouseenter="alert();" ng-mouseleave="text();"> {{value}} </button>
</body>
</html>

How do I make a scope function work when using ng-include?

<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="keyboard.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link href='http://fonts.googleapis.com/css?family=Roboto+Slab|Roboto' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="keyboard.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-include src="'keyboard.html'"></div>
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
$scope.insertString = function(letter) {
//$scope.name = $scope.name + letter;
$scope.name = [$scope.name.slice(0,$scope.cursorPosVal),letter,$scope.name.slice($scope.cursorPosVal)].join('');
console.log($scope.name);
setTimeout(function(){ setCaretPosition("inputBox", $scope.cursorPosVal); }, 30);
};
</script>
</body>
</html>
I know this is a bit thrown together, (the main code is just an example app from w3schools) but it shows what I am trying to do. So I have a keyboard app that I am bringing into the file (ng-include) and it appears absolutely wonderfully. My issue is that $scope is not being recognized. I have read the "Understanding Scopes" github document but it is just a bit much for me to take in. If someone could explain what I need to do to make sure that all of my $scope functions actually function, I would appreciate it greatly.
as Fissio said in the comments, you have a scope function declared outside of your controller:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
/**** see this here ****/
$scope.insertString = function(letter) {
//$scope.name = $scope.name + letter;
$scope.name = [$scope.name.slice(0,$scope.cursorPosVal),letter,$scope.name.slice($scope.cursorPosVal)].join('');
console.log($scope.name);
setTimeout(function(){ setCaretPosition("inputBox", $scope.cursorPosVal); }, 30);
};
this is what you need:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.insertString = function(letter) {
//$scope.name = $scope.name + letter;
$scope.name = [$scope.name.slice(0,$scope.cursorPosVal),letter,$scope.name.slice($scope.cursorPosVal)].join('');
console.log($scope.name);
setTimeout(function(){ setCaretPosition("inputBox", $scope.cursorPosVal); }, 30);
};
});
you can't use the keyword $scope outside of your controller because its bound to your controller. When it's outside angular will not know what it is that's why it will say something like it's not recognized

AngularJs broadcast event

I want to broadcast angular event from javascript function i.e angular.injector(['ng', 'myModule']).get("mySharedService").prepForBroadcast('hello');
By using above line I can invoke prepForBroadcast() but I can't catch event in $scope.$on()
Note: I want to call prepForBroadcast() method from javascript function.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<!-- SPELLS -->
<!-- load angular via CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="script.js"></script>
<style>
.question{
border:1px solid darkgray;
padding:10px;
margin-bottom:10px;
}
</style>
</head>
<body>
<div ng-app="myModule">
<div id="appID" ng-controller="ControllerZero">
<input ng-model="message" >
</div>
<div ng-controller="ControllerOne">
<input ng-model="message" >
</div>
<div ng-controller="ControllerTwo">
<input ng-model="message" >
</div>
<my-component ng-model="message"></my-component>
</div>
</body>
<script>
angular.injector(['ng','myModule']).get("mySharedService").prepForBroadcast('hello');
</script>
</html>
script.js file
var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function(msg) {
console.log('prepForBroadcast');
this.message = msg;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
console.log('broadcastItem');
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
myModule.directive('myComponent', function(mySharedService) {
return {
restrict: 'E',
controller: function($scope, $attrs, mySharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'Directive: ' + mySharedService.message;
});
},
replace: true,
template: '<input>'
};
});
function ControllerZero($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
console.log('handle event');
$scope.message = sharedService.message;
});
}
function ControllerOne($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'ONE: ' + sharedService.message;
});
}
function ControllerTwo($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'TWO: ' + sharedService.message;
});
}
ControllerZero.$inject = ['$scope', 'mySharedService'];
ControllerOne.$inject = ['$scope', 'mySharedService'];
ControllerTwo.$inject = ['$scope', 'mySharedService'];
angular.injector() creates a new injector, and with it a new $rootScope. The event will be broadcasted on this new $rootScope instead of on the one your controllers are listening on.
You need to retrieve the injector already associated with your application:
angular.element(domElement).injector();
You also need to manually trigger the digest loop for the data bindings to update, for example by using $apply.
Example:
angular.element(document).ready(function() {
var element = angular.element(document.querySelector('.ng-scope'));
var injector = element.injector();
var scope = element.scope();
scope.$apply(function() {
injector.get('mySharedService').prepForBroadcast('hello');
});
});
Demo: http://plnkr.co/edit/NDKBdzSmvN1xY7alafir?p=preview
Another way of publishing events from one controller and listening them in other controllers would be to use angular-PubSub module.
The PubSub makes only subscribers to listen to the published events unlike the $rootScope.$broadcast in which it sends event to all the Scopes in Scope hierarchy making it inefficient as compared to the PubSub approach.

Categories

Resources