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
Related
I would like to call a server-side service when my filter is empty.
this is my HTML:
<html lang="en">
<head>
<meta charset="utf 8">
<title>test angular</title>
</head>
<script src="https://code.angularjs.org/1.6.9/angular.js"></script>
<body ng-app="app">
<h1 ng-app="app" ng-controller="HelloWorldCtrl">{{message}}</h1>
<p><input type="text" id="myfilter" ng-model="seachText"></p>
<div ng-app="app" id="search" ng-controller="serviceCall">
<ul>
<li ng-repeat="x in lau | myfilter:seachText">
{{ x.des }}
</li>
</ul>
</div>
and this is my code:
var app = angular.module("app", []);
app.controller("serviceCall", function($scope, $http) {
var v=document.getElementById('search').value;
if (!v){v="Vigo";}
$http.get("http://127.0.0.1/KLAU.pl?search="+v+"&lim=10").then(function(response) {
$scope.lau = response.data;
});
});
app.filter('myfilter', [function($scope){
return function(input, param) {
if(!angular.isDefined(param)) param = '';
var ret = [];
angular.forEach(input, function(v){
var regx=new RegExp(param, 'gi');
if(regx.test(v.des)){
ret.push(v);
console.log("match!!");
}
});
if (!ret.length ){
$scope.serviceCall();
}
return ret;
};
}]);
I'm getting:
typeError: "$scope is undefined".
thanks in advance for the help.
$scope does not work in filter. Better inject a service, or pass the service function as another parameter to the filter:
return function(input, param, serviceCall) {
//...
serviceCall() // replaces $scope.serviceCall();
//...
}
Make sure you define serviceCall in the controller that calls the filter:
app.controller("serviceCall", function($scope, $http) {
var v=document.getElementById('search').value;
if (!v){v="Vigo";}
$scope.serviceCall = function() {
$http.get("http://127.0.0.1/KLAU.pl?search="+v+"&lim=10").then(function(response) {
$scope.lau = response.data;
});
};
$scope.serviceCall();
});
});
In HTML:
<li ng-repeat="x in lau | myfilter:seachText:serviceCall">
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+.
here we go...
I have a controller
$scope.selectedScript = {};
$scope.selectedScript.scriptId = null;
$scope.selectScript = function(script, index) {
$scope.selectedScript = script;
$scope.selectedRow = index;
myAppFactory.updateTextArea(script).success(
function(data) {
$scope.selectedScript = data;
});
};
$scope.getSelectedClass = function(script) {
if ($scope.selectedScript.scriptId != undefined) {
if ($scope.selectedScript.scriptId == script.scriptId) {
return "selected";
}
}
return "";
};
i have a html page
<label>Script ID:</label>
<input name="scriptId"
type="text"
id="scriptId"
ng-model="selectedScript.scriptId"
ng-disabled="true"
value="{{selectedScript.scriptId}}" />
and now thx to IARKI i have this
<script type="text/javascript">
function goTo (){
var param1 = angular.element(document.querySelector('.scriptId')).scope.selectedScript.scriptId;
location.href=this.href + '?scriptId='+param1;
return false;
}
</script>
Debug
I have also a list of scripts in a table
<table class="scripts" name="tableScript" arrow-selector>
<tr bgcolor="lightgrey">
<th>Script ID</th>
<th>File Name</th>
</tr>
<tr
ng-repeat="s in scripts | filter:searchField | orderBy:'scriptId'"
ng-click="selectScript(s, $index)" ng-class="getSelectedClass(s)">
<td>{{s.scriptId }}</td>
<td>{{s.fileName }}</td>
</tr>
</table>
Then i press the link above, and a new tab appears, but the link is still the
http://localhost:8080/DSS-war/debug.html
but i need it to open in a new tab as well as to be like this:
http://localhost:8080/DSS-war/debug.html?scriptId=1
http://localhost:8080/DSS-war/debug.html?scriptId=2
http://localhost:8080/DSS-war/debug.html?scriptId=12
and so on...with numbers
any idea?
And it has to be the onclick function, not the ng-click
I know how it works on ng-click, but i need to make it work on onclick...
and now i get this from the chrome debugger:
Uncaught TypeError: Cannot read property 'scriptId' of undefined
in the line
var param1 = angular.element(document.querySelector('.scriptId')).scope.selectedScript.scriptId;
You can try to access angular scope using pure javascript
<script type="text/javascript">
function goTo (){
var param1 = angular.element("#scriptId").scope().selectedScript.scriptId;
location.href=this.href + '?scriptId='+param1;
return false;
}
</script>
Debug
Update
Useless code but I hope it will help you
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>My application</title>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<label>Script ID:</label>
<input name="scriptId" type="text" id="scriptId" ng-model="selectedScript.scriptId" ng-disabled="true">
<button onclick="generateID()">Set code</button>
Debug
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script type="text/javascript">
function generateID() {
var code = Math.floor(Math.random() * 20) + 1;
document.getElementById('scriptId').setAttribute('value', code.toString());
}
function goTo() {
var scope = angular.element(document.querySelector('#scriptId')).scope();
scope.$apply(function () {
scope.selectedScript.scriptId = document.querySelector('#scriptId').getAttribute('value');
});
scope.changeURl();
}
angular.module('myApp', [])
.controller('myCtrl', function ($scope, $window) {
$scope.selectedScript = {};
console.log('We are in controller');
$scope.changeURl = function () {
$window.open('http://localhost:8080/DSS-war/debug.html?scriptId=' + $scope.selectedScript.scriptId, '_blank');
}
});
</script>
</html>
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.
I am writing code in Angular JS implement a standard application which would show a search field and a search button the screen and when a search is run, it should pull in the remote result and display them on the screen
Console is not showing any errors to me but i cant get to display the results on the screen.I am wondering how do i display the results on the screen
here is the code in my js file
angular.module('plunker', [])
.controller('MainCtrl', ['$scope', '$http',
function($scope, $http) {
var clearError = function(result) {
$scope.error = "";
return result;
};
var applyData = function(result) {
$scope.articles = result.data;
console.log(result.data);
};
var rejected = function(error) {
$scope.error = error.message;
};
var getArticles = function() {
var url = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=North+Korea&api-key=052861d142cf4eb7fa12bb79781fdbe1:11:69591426";
var promise = $http({
method: 'GET',
// https://jsonp.nodejitsu.com
url: "https://jsonp.nodejitsu.com/?url=" + encodeURIComponent(url)
});
promise.success(clearError).then(applyData);
promise.error(function(error) {
$scope.error = error.message;
});
};
getArticles();
$scope.getRepos = _.debounce(getArticles, 300);
}]);
And here is the html code
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="lodash.js#*" data-semver="2.4.1" src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
<script data-require="angular.js#1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.17"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<input ng-keyup="getArticles()" />
<table>
<thead>
<tr>
<td>Headline</td>
<td>Body</td>
</tr>
</thead>
<tbody>
<tr ng-bind="error" style="color:red;"></tr>
<tr ng-repeat="a in Articles">
<td>{{a.headline}}</td>
<td>{{a.body}}</td>
</tr>
</tbody>
</table>
</body>
</html>
You have several issues.
In scope you have articles but in html it is Articles.
To access the actual data you want in response you need to look deeper inside the data object returned:
Try changing:
var applyData = function(result) {
$scope.articles = result.data;
console.log(result.data);
};
To:
var applyData = function(result) {
var articles=result.data.response.docs
$scope.articles = articles;
console.log(articles);
};
Then in the html you need slightly different properties since headline has sub properties like main and print_headline
As example
<tr ng-repeat="a in articles">
<td>{{a.headline.main}}</td>
<td>{{a.lead_paragraph}}</td>
</tr>
DEMO