Angular 2-Way Binding - angularjs

I have been having this issue with Controllers in Angular. I looked it up as much as possible, but I could not resolve the issue.
I am trying to implement a simple controller, but for the life of me, I cannot get the binding to work. It's not displaying my data. For example when I say, {{ test }}, I get just that, not the "Hello World!" string.
var app = angular.module('App', []);
app.controller('Hi', function($scope){
$scope.hello = "hello!";
});
app.controller('todoCtrl', ['$scope', '$http', function($scope, $http) {
$scope.test = "Hello World!";
$scope.formData = "";
$http.get('/api/todos')
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
$scope.createTodo = function() {
$http.post('/api/todos', $scope.formData)
.success(function(data) {
$scope.formData.text = "";
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.deleteTodo = function(id) {
$http.delete('/api/todos/' + id)
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}]);
<!DOCTYPE html>
<html ng-app="App">
<head>
<title>TodoX</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<!-- TodoX CSS -->
<link rel="stylesheet" type="text/css" href="stylesheets/style.css"/>
</head>
<body ng-controller="todoCtrl">
<div class="container">
<div class="row">
<div class="jumbotron text-center">
<h1>TodoX<span>{{todos.length}}</span>{{test}}</h1>
</div>
<div class="col-md-8">
<div class="list-group">
<div class="checkbox" ng-repeat="todo in todos | orderBy:date">
<label class="list-group-item">
<input type="checkbox"/> {{todo.text}}
</label>
</div>
</div>
</div>
<div class="col-md-4">
<form class="form-group">
<input type="text" class="form-control" ng-model="formData"/>
<input type="submit" ng-click="createTodo()" placeholder="Submit" class="form-control"/>
</form>
</div>
</div>
</div>
<!-- Angular JS -->
<script type="text/javascript" href="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<!-- TodoX Core JS -->
<script type="text/javascript" href="core.js"></script>
</body>
</html>

I just executed your code while placing angular file link above the script tag, so that AngularJs is loaded before your script can call angular modules.
I think you're putting angular after your script which is why you are running into this issue. Your code works just fine. I tested it.
Put it like this
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="script.js"></script>
Here script.js will be your controller script.
Working fiddle

Related

Passing scope data to Google charts in AngularJS

I am working on a stock application using Spring Boot. I have stock data from external API which looks like this:
{{stock.dates}} = [2017-05-04, 2017-05-03, 2017-05-02, 2017-05-01,
2017-04-28, 2017-04-27, 2017-04-26, 2017-04-25, 2017-04-24, 2017-04-21]
{{stock.stockValues}} = [150.85, 151.8, 152.78, 152.46, 150.25, 147.7,
146.56, 146.49, 145.47, 143.68]
My index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Stock app</title>
<script>
<!-- Many scripts here-->
</script>
</head>
<body ng-app="App">
<navbar-menu></navbar-menu>
<div class="container" ng-view></div>
</body>
</html>
My stock.html:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
<!-- Many scripts here-->
</script>
</head>
<body>
<div id="spinner" class="spinner" ng-show="loading">
<img src="https://www.yugma.com/images/loading-animation-7.gif" />
</div>
<!-- Page Content -->
<div class="container" ng-show="content">
<div class="panel">
<div class="container">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4"></div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-2">
<h5>Stock symbol:</h5>
</div>
<div class="col-md-1">{{stock.symbol}}</div>
<div class="col-md-9"></div>
</div>
<div class="row">
<div class="col-md-2">
<h5>Last refreshed:</h5>
</div>
<div class="col-md-3">{{stock.lastRefreshed}}</div>
<div class="col-md-8"></div>
</div>
<div class="row">
<div class="col-md-2">
<h5>Last price:</h5>
</div>
<div class="col-md-3">{{stock.stockValues[0]}}</div>
<div class="col-md-8"></div>
</div>
</div>
</div>
</div>
My controller.js:
(function(angular) {
'use strict';
var App = angular.module('App');
App.controller('StockController', [ '$scope', '$http', '$routeParams',
'$rootScope', function($scope, $http, $routeParams, $rootScope) {
$scope.init = function() {
if ($rootScope.stockID !== undefined) {
$scope.getStockData($rootScope.stockID);
return;
} else if ($routeParams.stockID !== undefined) {
$rootScope.stockID = $routeParams.stockID;
} else {
$rootScope.stockID = 'FB';
}
$scope.getStockData($rootScope.stockID);
};
$scope.getStockData = function(stockID) {
$scope.loading = true;
$scope.content = false;
$http.get('/stock', {
params : {
stockID : encodeURI(stockID)
}
}).then(function(response) {
$scope.showError = false;
$scope.stock = response.data;
$scope.stockAvailable = true;
}, function(response) {
$scope.showError = true;
}).finally(function() {
// called no matter success or failure
$scope.loading = false;
$scope.content = true;
});
};
$scope.init();
} ]);
})(window.angular);
Now what I need to do is to create a Google Chart using this data (dates vs stock values)
How can I do it?
Also, when I tried to draw a static example chart from Google Charts Tutorial I could only do it in my index.html, when I put the same definition in stock.html, the chart didn't work, do you have any idea why?

Getting data from metaweather API to angularjs page

I'm building a simple weather app that gets the weather for any city.
For this API there are two stages:
1) you enter a name of a city, get its "where on earth ID" (woeid).
2) use the woeid to search for the weather.
This is the API: https://www.metaweather.com/api/
For example:
https://www.metaweather.com/api/location/search/?query=london
You get this JSON:
[{"title":"London","location_type":"City","woeid":44418,"latt_long":"51.506321,-0.12714"}]
For starters, just to get the woeid would be great.
It fails to connect to the API but when i type it manually it works.
app.js:
var app = angular.module('weatherApp', []);
app.controller('weatherCtrl', ['$scope', 'weatherService', function($scope, weatherService) {
function fetchWoeid(city) {
weatherService.getWoeid(city).then(function(data){
$scope.place = data;
});
}
fetchWoeid('london');
$scope.findWoeid = function(city) {
$scope.place = '';
fetchWoeid(city);
};
}]);
app.factory('weatherService', ['$http', '$q', function ($http, $q){
function getWoeid (city) {
var deferred = $q.defer();
$http.get('https://www.metaweather.com/api/location/search/?query=' + city)
.success(function(data){
deferred.resolve(data);
})
.error(function(err){
console.log('Error retrieving woeid');
deferred.reject(err);
});
return deferred.promise;
}
return {
getWoeid: getWoeid
};
}]);
index.html:
<!DOCTYPE html>
<html ng-app="weatherApp">
<head>
<meta charset="utf-8" />
<title>Weather App</title>
<link data-require="bootstrap-css#3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<script>document.write('<base href="' + document.location + '" />');</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script data-require="jquery#*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap#*" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="weatherCtrl">
<form>
<div class="form-group">
<input class="form-control" type="text" ng-model="city" placeholder="e.g. london" />
<input class="btn btn-default" type="submit" value="Search" ng-click="findWoeid(city)" />
</div>
</form>
<p ng-show="city">Searching the forecasts for: {{city}}</p>
<div>
<h1>WOEID is: {{ place }}</h1>
<a ng-click="findWeather('london'); city = ''">reset</a>
</div>
</body>
</html>
It appears you are having a Cross Origin problem. It doesn't look like Metaweather supports JSONP, so the fix for this is a bit more complex. You need to be running your page through a server that can support a proxy. One such example is https://www.npmjs.com/package/cors-anywhere. If you set that up using the defaults then change your AJAX call to:
$http.get('http://localhost:8080/https://www.metaweather.com/api/location/search/?query=' + city)

Angularjs Error :Uncaught Error: [$injector:modulerr]

I am making an AngularJS app,in which I am using Express as backend. The problem is,whenever I run my app
angular.js:36Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.0-beta.14/$injector/modulerr?p0=starter&p1=….com%2Fajax%2Flibs%2Fangularjs%2F1.3.0-beta.14%2Fangular.min.js%3A18%3A139)
Above error occurs in browser's console. I have tried many solutions but none of them worked.
My index.html is
<!DOCTYPE html>
<html ng-app="starter">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>AngularJS Routing example</title>
<script src="hhtp://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></script>
<script src="http://localhost/try/www/js/ng-cordova.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3">
<ul class="nav">
</ul>
</div>
<div class="col-md-9">
<div ng-view></div>
</div>
</div>
</div>
<script src="http://localhost/try/www/js/app.js"></script>
<script src="http://localhost/try/www/js/master_serverquery.js"></script>
<script src="http://localhost/try/www/js/employeeCtrl.js"></script>
</body>
</html>
My login.html is
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8">
<title>Daily UI - Day 1 Sign In</title>
<link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700|Lato:400,100,300,700,900' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="http://localhost/try/www/css/animate.css">
<link rel="stylesheet" href="http://localhost/try/www/css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></s‌​cript>
<script src="http://localhost/try/www/js/ng-cordova.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js"></script>
</head>
<body ng-app="starter" >
<div ng-controller="loginCtrl">
<div class="top">
<h1 id="title" class="hidden"><span id="logo"></span></h1>
</div>
<div class="login-box animated fadeInUp">
<div class="box-header">
<h2>Log In</h2>
</div>
<form method="POST">
<label for="username">Username</label>
<br/>
<input type="text" name = "login" ng-model="loginId">
<br/>
<label for="password">Password</label>
<br/>
<input type="password" name = "password" ng-model = "loginPassword" >
<br/>
<button type="submit" ng-click = "loginFunc()">Sign In</button>
<br/>
Add New Order
</form>
<p class="small">Forgot your password?</p>
</div>
</div>
<script src="http://localhost/try/www/js/app.js"></script>
<script src="http://localhost/try/www/js/master_serverquery.js"></script>
</body>
</html>
My app.js is
var app = angular.module('starter', ['ngRoute','ngCordova']);
console.log("error")
app.run(function( $cordovaSQLite) {
db = window.openDatabase("marketplace.db", '1', 'my', 1024 * 1024 * 100);
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS user_master_vendor (server_db_column_id integer, name text)");
console.log("browser");
});
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'template/login.html',
controller: 'loginCtrl'
}).
otherwise({
redirectTo: '/login'
});
}]);
app.run(function($rootScope){
$rootScope.project_url = 'http://127.0.0.1:8081';
})
app.controller('loginCtrl',function($scope, $http, $rootScope ,$location, $cordovaSQLite){
$scope.loginFunc = function($scope){
var loginPassword = $scope.loginPassword;
var loginId = $scope.loginId;
console.log(" loginCtrl");
$scope.user = {
loginId : loginId,
loginPassword : loginPassword
}
alert($scope.user.loginId);
var loginUrl = $rootScope.project_url + '/login_post';
$http({
method : 'POST',
url : loginUrl,
headers: {
'Content-Type': undefined
},
params: {
loginId : loginId,
loginPassword : loginPassword
},
dataType: 'json',
processData : false
}).then(function successCallback(response) {
console.log(response.data.result[0].Emp_Id);
console.log(response.data.result[0].Emp_Password);
console.log("successCallback called");
var server_db_column_id = response.data.result[0].Id;
var user_name = response.data.result[0].Name;
$cordovaSQLite.execute(db, 'INSERT INTO user_master_vendor (server_db_column_id, name) VALUES (?, ?)',
[server_db_column_id, user_name])
.then(function(result) {
console.log("Data Saved Successfully in user_master at INSERT ID -> " + result.insertId);
console.log("Data user_empId-> " + user_empId + ", user_empPassword->" +user_empPassword);
},
function(error) {
$scope.showp = "Data could not be saved in user_master_vendor Error -> " + error.message;
console.log(error);
});
}, function errorCallback(response) {
alert("failure: "+response);
});
}
});
Thanks a lot for helping me.I have found the soultion for the problem,it required downloading angular-route module using npm.The below link helped me.
https://docs.angularjs.org/api/ngRoute
I followed all the steps and was able to solve the problem.

Loading image at the time of onclick event using angularjs is not working

I want to add data at the time of onclick event. Need to load image at the time of onclick event, after a small time interval add data. But my image is continuously loading. Any body give any suggestion.
My code is:
<!DOCTYPE html>
<head>
<title>Learning AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
<script language="javascript">
function ContactController($scope) {
$scope.contacts = [];
$scope.items = [ ];
$scope.add = function() {
setTimeout(function() {
$scope.$apply(function() {
$scope.items[0].lateLoader = ' xxxx ';
});
}, 1000);
$scope.count=$scope.count+1;
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
}
}
</script>
</head>
<body >
<div ng-app="" ng-controller="ContactController">
<p>{{items.lateLoader}}
<i ng-hide="items.lateLoader"><img src="Filling broken ring.gif"></i>
</p>
{{ contacts.length }}
Content:<input type="text" ng-model="newcontact" />
<button ng-click="add()">Add</button>
<ul style="list-style-type: none;">
<li ng-repeat="contact in contacts"> <input name="" type="checkbox" value="">{{ contact }}</li>
</ul>
</div>
</body>
</html>
In your example I found a lot of mistakes. The HTML tag is not defined at the top, wrong use of angularJs and Angular module is not created properly etc.
I fixed all the mistakes. I hope it can help you.
Plunkr link: http://plnkr.co/edit/no8WOHdEc9wc3dHzzITv?p=preview
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Learning AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script >
angular.module("app",[]).controller('ContactController',['$scope',
function($scope) {
$scope.contacts = [];
$scope.items = [];
$scope.add = function() {
setTimeout(function() {
$scope.$apply(function() {
$scope.items.lateLoader = 'xxxx ';
});
}, 1000);
//$scope.count=$scope.count+1;
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
}
}
]);
</script>
</head>
<body >
<div ng-controller="ContactController">
<p>{{items.lateLoader}}
<i ng-hide="items.lateLoader">
<img src="https://encrypted-tbn1.gstatic.com
/images?q=tbn:ANd9GcQTaHe0F0J39SXbiRF43pz2wtyfD6kypCMrLxhWPkq9EACNgwO0iaMbJFM">
</i>
</p>
{{contacts.length}}
Content:<input type="text" ng-model="newcontact" />
<button ng-click="add()">Add</button>
<ul style="list-style-type: none;">
<li ng-repeat="contact in contacts">
<input name="" type="checkbox" value="">{{ contact }}
</li>
</ul>
</div>
</body>
</html>
And for more detail of angularJs please visit these links:(https://angularjs.org/)
(http://www.w3schools.com/angular/default.asp)

Angular Js Basic Controller Return Error

Angular Controller return error when called through an app. But works when written directly.
My html code
<!DOCTYPE html>
<html ng-app>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="fbapp">
<div ng-controller="fbController" class="container">
<input type="text" name="name" ng-model="name"/>
<input type="button" value="Fetch" ng-click="fetchUser()" class="btn btn-primary"/>
</form>
</div>
</body>
</html>
My js code
var fbapp = angular.module('fbapp', []);
fbapp.controller('fbController', function($scope){
$scope.fetchUser = function() {
$scope.name = "Test";
}
}
Error I get
Error: [ng:areq] http://errors.angularjs.org/1.2.15/ng/areq?p0=fbController&p1=not%20a%20function%2C%20got%20undefined
at Error (native)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:6:450
at wb (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:18:360)
at Qa (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:18:447)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:65:470
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:52:156
at r (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:7:386)
at J (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:52:18)
at h (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:46:28)
at h (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:46:45)
It work for me if I don't declare container in a an app. Like...
function fbController ($scope){
$scope.fetchUser = function() {
$scope.name = "Test";
}
}
I am having no clue whats wrong.
as Stewie said you need to add closing parenthesis ' )'.
Example:
var app=angular.module('App', []);
app.controller('fbController', function($scope){
$scope.fetchUser = function() {
$scope.name = "Test";
}
})
html:
<div ng-app="App" >
<div ng-controller="fbController">
<button ng-click="fetchUser()">click</button>
<p >{{name}}</p>
</div>
</div>
Live example: http://jsfiddle.net/choroshin/7Ws6w/1/

Resources