AngularJS saving dynamic content to history - javascript

I'm new to AngularJS and I'm trying to make a home page that loads dynamic content from my database to create links. When I click one of those links on the home page, it sends a request to my node server and retrieves the appropriate data from the database and displays that on the partial view. When I'm on that partial view and I click the browser's back button to go back to the home page, the dynamic content that was originally loaded doesn't display. Below is my code. Why doesn't clicking the browser's back button redisplay the home page with the dynamic content?
index.html
<!doctype html>
<html lang="en" ng-app="phonecatApp">
<head>
<meta charset="utf-8">
<base href="/">
<title>My site</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/animations.css">
<script src="bower_components/jquery/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-animate/angular-animate.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="/js/animations.js"></script>
<script src="/js/controllers.js"></script>
<script src="/js/filters.js"></script>
<script src="/js/app.js"></script>
</head>
<body ng-controller="mainController">
<div class="container">
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/" ng-click="home()">Home</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
</ul>
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" data-provide="typeahead" autocomplete="off" placeholder="foo, bar" ng-model="query">
</div>
</form>
<ul class="nav navbar-nav navbar-right">
</ul>
</div>
</div>
</nav>
</div>
<div class="view-container">
<div ng-view class="view-frame"></div>
</div>
</body>
</html>
phone-detail.html
<div class="phone-images">
<img ng-src="{{thing.imageUrl}}" dclass="phone">
</div>
<h1> {{ things[0].name }} </h1>
<iframe id="viddy" width="560" height="315" ng-src="{{ things[0].embed }}" frameborder="0" allowfullscreen autoplay="1" ></iframe>
<p>source:</p>
<p>{{ things[0].vid }}</p>
</div>
phone-list.html
<div class="container-fluid">
<div class="row">
<div class="col-md-10">
<!--Body content-->
<div>
<div ng-if="things.length>1">
<ul class="phones">
<li ng-repeat="foo in things | filter:query"
class="thumbnail phone-listing">
<img ng-src="{{foo.imageUrl}}">
{{foo.name}}
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
//controller.js
'use strict';
/* Controllers */
var coreControl = angular.module('prjController', []);
coreControl.controller('mainController', ['$scope', '$http', '$sce', '$locationProvider'
function($scope, $http, $sce, $locationProvider)
{
//$scope.$on('$routeChangeSuccess', function(req, res) {console.log($route.current.params);})
$scope.formData = {};
$scope.things = [];
$scope.maxThings = 0;
$http.get('/things')
.success(function(data)
{
$scope.things = data;
$scope.maxThings = $scope.things.length;
console.log(data);
})
.error(function(data)
{
console.log('Error: ' + data);
});
$scope.home = function()
{
$http.get('/things')
.success(function(data)
{
$scope.things = data;
$scope.maxThings = $scope.things.length;
console.log(data);
})
.error(function(data)
{
console.log('Error: ' + data);
});
}
$scope.search = function(thing)
{
$http.get('/thing/'+thing, $scope.formData)
.success(function(data)
{
$scope.formData = {};
$scope.things = data;
$scope.msg = "Recommend a video."
$scope.noMatch = false;
if($scope.things.length == 0)
{
$scope.noMatch = true;
}
$scope.things[0].embed = $sce.trustAsResourceUrl($scope.things[0].embed+"?autoplay=0&showinfo=0&controls=0&loop=1");
document.getElementById('viddy').src = document.getElementById('viddy').src;
console.log(data);
})
.error(function(data)
{
console.log('Error: ' + data);
});
}
}]);
//app.js
'use strict';
var phonecatApp = angular.module('phonecatApp', [
'ngRoute',
'phonecatAnimations',
'prjController'
]);
phonecatApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/:thingId', {
templateUrl: 'partials/phone-detail.html'
}).
otherwise({
templateUrl: 'partials/phone-list.html'
});
}]);
//server.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var port = process.env.PORT || 8887;
var db = require('./config/db');
var connection = mysql.createConnection(db);
connection.connect();
app.configure(function()
{
app.use(express.static(__dirname + '/public'));
app.use(express.logger('dev'));
app.use(express.bodyParser());
});
require('./app/router')(app, connection);
app.listen(port);
exports = module.exports = app;
//router.js
module.exports = function(app, conn)
{
app.get('*', function(req, res){
var url = req.originalUrl;
if(url.match(/^\/thing\/.+/))
{
var query_thing = url.replace(/%20/g, ' ');
query_thing = query_thing.replace(/\/thing\//, '');
require('./search')(query_thing, res, conn);
}
else
{
require('./populate')(res, conn);
}
});
};
//populate.js
module.exports = function(res, connection)
{
function getRandIds(rep, max)
{
var ids = [];
//create a list of rep-many random integers, which may have repetitions
for (var i = 0; i < rep; i++)
{
ids.push(Math.floor(Math.random()*100) % max);
}
function numercalSort(a,b)
{
return a-b;
}
//sort() without the callback sorts alphabetically
ids.sort(numercalSort);
console.log(ids);
var notUnique = false;
//check that each id is unique so that the exact number of ids will be queried
for(var i = 0; i < ids.length; i++)
{
if(i+1 < ids.length && ids[i] == ids[i+1])
{
notUnique = true;
}
}
//recurse if the values are not all unique
if(notUnique)
{
ids = getRandIds(rep, max);
}
return ids;
}
//creates a query that searches for random ids
function queryRand(rep, max)
{
var sql = "select m.name, m.imageUrl, v.vid, v.embed from things as m, videos as v where m.id=v.id and (";
var ids = getRandIds(rep, max);
for(var i = 0; i < ids.length; i++)
{
sql += " m.id like "+ids[i];
if(i < ids.length - 1)
{
sql += " or";
}
else
{
sql += ");";
}
}
var sql = "select m.name, m.imageUrl, v.vid, v.embed from things as m, videos as v where m.id=v.id";
return sql;
}
//handles the output
function handleOut(err, result, fields)
{
if(err) throw err;
console.log('rand results: ',result);
res.json(result);
}
var repetitions = 10; //number of things to display
var totalCount = 372; // total number of things in the database
var sql = queryRand(repetitions, totalCount);
connection.query(sql, handleOut);
};

So after a long while, I finally realized that the issue was that I only had one controller that held the functionality for all my controllers. That was only loading once. Because it only loaded once, the $http.get('/things') call was only being made that once when the controller initially loaded. To resolve this, I separated out my controllers. I made one specifically for my home page, and made a separate partial for it and placed the controller specifically in that partial, so it loads every time the partial loads.
This also required updating the index.html and app.js, appropriately.
//mainController.js
angular.module('prjController', [])
.controller('mainController', ['$scope', '$http', '$sce',
function($scope, $http, $sce)
{
$http.get('/things')
.success(function(data)
{
$scope.things = data;
$scope.maxThings = $scope.things.length;
console.log(data);
})
.error(function(data)
{
console.log('Error: ' + data);
});
}]);
<!-- main.html partial -->
<div class="container-fluid" ng-controller="mainController">
<!--Body content-->
...
</div>

Related

angularjs custom filter dynamic server call

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">

Update Data from Calculator - NodeJS + AngularJS

I am new to JS development. I found a nodejs calculator project on github that I've been manipulating.
My Problem: In my calculator, I'm trying to combine all of my results together. However, the data of my old entries are still present, I would like to remove these old entries and have it update instead with the most up-to-date entry.
I know it has something to do with data-ng-repeat (shown in my index code below), but I've tried other directives and they haven't worked. Is there something I need to change in my code to use a different directive?
Here's what I am working with, everything works well until the last screenshot:
Widget calculator
https://imgur.com/a/2ebpyym
Specific Widget Selection
https://imgur.com/a/STYeLcF
Entering QTY of Widgets
https://imgur.com/a/B5ii32J
Calculation Result #1 (1 Sheet is worth 8 Widgets)
https://imgur.com/a/CUouHAt
Problem: Calculation Result #2
https://imgur.com/a/XJrclUY
In the above link, I would prefer if the "62.5" in the "Combined Sheets Needed" section is replaced by "93.75"
Code
server.js
'use strict';
const express = require('express');
const app = express();
let PORT = process.env.PORT || 3000;
console.log('hello1')
let operators = [
{name:'24x24 Widget', symbol:'24x24 Widget'}
];
function calculate(operator, value1, value2) {
if ( operator == '24x24 Widget' ) return value1 /8 + " sheets";
}
app.use(express.static(__dirname + '/build'));
app.use(require('body-parser').json());
app.use((req, res, next) => {
// res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Origin', 'https://mean-calculator.herokuapp.com/calculator');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
next();
});
app.listen(PORT, () => {
console.log('server started on port', PORT);
});
var array = [];
app.route('/calculator')
.get((req, res) => {
res.json({
operators
});console.log('hello in route')
array = [];
})
.post((req, res) => {
let operator = req.body.operator.name;
let value1 = req.body.value1;
let result = calculate(operator, value1);
array.push(value1/8);
console.log(array);
var sum = array.reduce(function(a, b) { return a + b; }, 0);
console.log(sum, 'this is the sum');
let doubleresult = calculate(operator, value1*2)
res.json({
result: {
operator: req.body.operator.symbol,
value1,
result,
sum
}
});
});
index.html
(Check comment: <!-- Combining Data Here-->)
<!DOCTYPE html>
<html data-ng-app="App">
<head>
<meta charset="utf-8">
<link href='https://fonts.googleapis.com/css?family=Open+Sans|Lora|Lato:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="main.css" charset="utf-8">
<title>Widget Calculator</title>
</head>
<body data-ng-controller="AppController as appCtrl"></body>
<h1>Solve for Material Needed for Widgets</h1>
<div class="solve">
<h2 data-ng-show="appCtrl.error" class="error">{{appCtrl.error}}</h2>
<form method="post">
<h2>Select a Widget</h2>
<select data-ng-model="operator" data-ng-options="operatorOption.name for operatorOption in appCtrl.operators">
<option value="">-- choose Widget --</option>
</select>
<h2>Select QTY</h2>
<input data-ng-model="value1" type="number" placeholder="1st Number">
<span>{{operator.symbol}}</span>
<span></span>
<button data-ng-click="appCtrl.calculate(operator, value1, value2); value1=undefined; value2=undefined; operator=undefined" type="button">Calculate</button>
</form>
</div>
<div data-ng-show="appCtrl.results.length">
<h1>Results</h1>
<div class="result">
<h2 data-ng-repeat="result in appCtrl.results">{{result.value1}} {{result.operator}} = {{result.result}}</h2>
</div>
</div>
<!-- Combining Data Here-->
<div data-ng-show="appCtrl.results.length">
<h1>Combined Sheets Needed</h1>
<div class="result combined">
<h2 data-ng-repeat="result in appCtrl.results">{{result.sum}}</h2>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.6/angular.js" charset="utf-8"></script>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
app.js
var app = angular.module('App', []);
app.controller('AppController', ['$http', function($http) {
var apiRoute = 'http://localhost:3000/calculator';
var _this = this;
_this.results = [];
_this.operators = [];
$http.get(apiRoute)
.then(function(res) {
_this.operators = res.data.operators;
}, function(res) {
console.log(res);
});
_this.calculate = function(operator, value1, value2) {
_this.error = validate(operator, value1, value2);
if (!_this.error) {
$http.post(apiRoute, {operator, value1, value2})
.then(function(res) {
_this.results.push(res.data.result);
}, function(res) {
console.log(res);
});
}
}
}]);
function validate(operator, value1, value2) {
if (!operator) return 'Please select an operator.';
if ((!value1 && value1 != 0) || (!value1 && value1 != 0)) return 'Please enter two numbers.';
return null;
}

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

What is the preferred AngularJS way of adding CSS styling after Controller asynchronous call?

I am building an application with NW.js and AngularJS GitHub Link
My application retrieves file names from local folders and displays these filenames in the application as a list. I want the first item in the list look different from the rest because it starts as the "selected" button/item. The file data is asynchronous.
Currently, I have the file data loaded as a service which pulls the file names inside of the controller. Because the file data uses an asynchronous function, I have placed this within a async.series call within the controller. After this async call finishes, the ng-bind takes effect and the list is displayed in my app.
I have tried adding different directives to add the selected class to the first item but they all get called before the list is shown on the screen.
Can someone help me understand what is the preferred angularjs way of setting classes or css properties of an element after it has been binded to the data?
Below is the relevant code. For the full project follow the GitHub link above.
Controller
fileVizApp.controller("fileVizController", function ($scope, configs, consoles, $location) {
var async = require('async');
var filehelper = require('filehelper');
var consoleKeys = [];
for(var key in consoles) {
consoleKeys.push(key);
}
async.each(consoleKeys, function(currConsole, callback) {
filehelper.GetItemList(consoles, currConsole, callback);
var a = 9;
}, function(err) {
if(err) {
return next(err);
}
$scope.headerSrc = "tmpl/header.html";
$scope.configs = configs;
$scope.back = function () {
window.history.back();
};
$scope.getCount = function (n) {
return new Array(n);
}
$scope.isActive = function (route) {
return route === $location.path();
}
$scope.isActivePath = function (route) {
return ($location.path()).indexOf(route) >= 0;
}
$scope.$apply( function () {
$scope.consoles = consoles;
if(consoles.length > 0) {
$scope.currConsoleInd = 0;
if(consoles.length > 1) {
$scope.nextConsoleInd = 1;
$scope.prevConsoleInd = consoles.length - 1;
} else {
$scope.nextConsoleInd = -1;
$scope.prevConsoleInd = -1;
}
}
else {
$scope.nextConsoleInd = -1;
$scope.prevConsoleInd = -1;
}
});
$scope.$broadcast("Consoles_Ready");
});
});
Relevant HTML
<!-- index.html -->
<!DOCTYPE html>
<html data-ng-app="fileVizApp">
<head>
<title>File Visualizer</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/app.css">
<link rel="stylesheet" type="text/css" href="css/sidebar.css">
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/angular-resource.min.js"></script>
<script type="text/javascript" src="js/lib/angular-route.min.js"></script>
<script type="text/javascript" src="js/lib/jquery.min.js"></script>
<script type="text/javascript" src="js/lib/bootstrap.min.js"></script>
<script type="text/javascript" src="js/lib/ui-bootstrap-custom-tpls-0.13.0.min.js" ></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/service/services.js"></script>
<script type="text/javascript" src="js/controller/controllers.js"></script>
<script type="text/javascript" src="js/router/routes.js"></script>
<script type="text/javascript" src="js/directive/directives.js"></script>
</head>
<body class="container" data-ng-controller="fileVizController" main-directive>
<div data-ng-include src="headerSrc"></div>
<div id="container">
<div data-ng-view=""></div>
</div>
</body>
</html>
<!-- home.html-->
<div class="">
<!-- Sidebar -->
<ym-gamelist/>
<!-- /#sidebar-wrapper -->
</div>
<!-- itemlist.html -->
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<div ng-repeat="thisConsole in consoles">
<div ng-repeat="item in thisConsole.items" button-repeat>
<li>
<a class="itembutton" href="#"><span ng-bind="item"></span></a>
</li>
<li class="divider"></li>
</div>
</div>
</ul>
</div>
Directives
fileVizApp.directive('ymGamelist', function() {
return {
restrict: 'AE',
scope: {},
controller: 'fileVizController',
link: function(scope, element, attrs) {
scope.$on('Consoles_Ready', function () {
var newa = 1;
});
},
compile: function (element, attrs) {
return {
pre: function(scope, iElem, iAttrs){
console.log(name + ': pre link => ' + iElem.html());
},
post: function(scope, iElem, iAttrs){
console.log(name + ': post link => ' + iElem.html());
}
}
},
templateUrl: 'tmpl/itemlist.html'
};
});
fileVizApp.directive('buttonRepeat', function($compile) {
return function(scope, element, attrs) {
if(scope.$last) {
scope.$emit('Itemlist_Loaded');
}
};
});
fileVizApp.directive('mainDirective', function() {
return function(scope, element, attrs) {
scope.$on('Itemlist_Loaded', function (event) {
$('.gamebutton').first().addClass('selectedbutton');
});
};
});
Use the $first variable available inside ng-repeat together with ng-class to do this. Something like this
<div ng-repeat="item in thisConsole.items" button-repeat>
<li>
<a class="itembutton" href="#" ng-class={'selectedbutton':$first}><span ng-bind="item"></span></a>
</li>
<li class="divider"></li>
</div>

ng-view not show with Route (angularjs)

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.

Categories

Resources