angular js not displaying anything even like simple expressions. i am tying to execute below code but no hope. can anyone help me out.
below code is for view to display.
`<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript" src="/../../Scripts/angularsample.js"></script>
</head>
<body ng-app="spiceApp">
<div>
<div ng-controller="SpicyController">
<p> lets try some code by using service </p>
<input ng-init="message='Girish'" ng-model="message" />
<button ng-click="notify(message);">Notify{{1+2}}</button>
<p>alert will display only by clicking three times.</p>
</div>
<div ng-controller="List">
<button ng-click="bringList()">getList</button>
<table>
<tr ng-repeat="app in appslist">
<td>
{{app.Name}}
</td>
</tr>
</table>
</div>
</div>
</body>
</html>`
js code
var myApp = angular.module('spiceApp', []);
myApp.controller('SpicyController', ['$scope', '$http', 'userService', , function ($scope, $http, userService) {
//below code is using sservice
$scope.notify = function (msg) {
userService(msg);
};
}]);
myApp.controller('List', ['$scope', 'getList', function ($scope, getList) {
$scope.bringList = function () {
getList.getAppsList().then(function (list) {
$scope.appslist = list;
});
};
}]);
myApp.factory('getList', ['$http',function ($http) {
//this code for getting list from controller.
return getList.getAppsList=function(){
$http({
method: 'GET',
url: 'Home/GetAppsList'
})
.success(function (response) {
return response.data;
}, function (error) {
console.log(error);
});
}
}]);
myApp.factory('userService', ['$window', function (win) {
var msgs = [];
return function (msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join('\n'));
msgs = [];
}
};
}]);`
please tell me where i am wrong. nothing is working. expression is displaying like {{1+2}} in the ouptut.
You have a typo here:
myApp.controller('SpicyController', ['$scope', '$http', 'userService', , function
with the 2 comas so the dependancies are messed up.
i tried in different way with same view but i modified the js file now it's working fine.
var myApp = angular.module('spiceApp', []);
myApp.controller('SpicyController', ['$scope', '$http', 'userService',function ($scope, $http, userService) {
//below code is using sservice
$scope.notify = function (msg) {
userService(msg);
};
}]);
myApp.factory('userService', ['$window', function (win) {
var msgs = [];
return function (msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join('\n'));
msgs = [];
}
};
}]);
myApp.controller('List', ['$scope', 'getList', function ($scope, getList) {
$scope.bringList = function () {
getList.getAppsList.then(function (data) {
$scope.appslist = data;
});
};
}]);
var getList = angular.module("spiceApp").factory("getList", ['$http', function ($http, getList) {
return {
getAppsList: (function (response) {
return $http({
method: 'GET',
url: 'GetAppsList'
})
.then(function (response) {
console.log("coming from servicejs", response.data);
//return data when promise resolved
//that would help you to continue promise chain.
return response.data;
});
})()
};
return getList;
}]);
Related
I am trying to create a factory to retrieve weather data for a simple web page I am creating but, I am getting stuck when trying to call the function in the factory. I have fallowed Dan Wahlin's course on Udemy but I just cant figure out why I am getting the error. It definitely seems like I am doing something wrong but I can't figure it out.
Here is code
HTML
<!DOCTYPE html>
<div ng-controller="WeatherController" style="position:absolute; top:0px; ">
{{weather.weather.main}}<br>
<img src='http://openweathermap.org/img/w/10d.png' height="100px" width="100px">
</div>
<div style="background-color:white; position: absolute; bottom:0px;">
<canvas id="canvas" width="400" height="400">
</canvas>
</div>
<script src="script/angular.min.js"></script>
<script src="app/app.js"></script>
<script src="app/services/WeatherFactory.js"></script>
<script src="app/controllers/WeatherController.js"></script>
<script src="script/clock.js"></script>
app.js
(function () {
angular.module('displayApp', []);
}());
WeatherController.js
(function () {
var WeatherController = function ($scope, $log, $http, weatherFactory) {
$scope.weather = "";
function init() {
weatherFactory.getWeather() //******This line stops with error*****
.then(function (response) {
$scope.weather = response.data;
}, function (data, status, headers, config) {
$log.log(data.error + ' ' + status);
});
// $scope.weather = "Get the weather?"
}
init();
};
WeatherController.$inject = ['$scope', 'weatherFactory'];
angular.module('displayApp').controller('WeatherController', WeatherController);
}());
WeatherFactory.js
(function () {
var weatherFactory = function ($http) {
var factory = {};
factory.getWeather = function () {
//return $http.get('api.openweathermap.org/data/2.5/weather?q=Rancho Santa Margarita&appid=60f84f7ee9256ef5057de8b616105ab9');
return "Get the weather";
};
return factory;
};
weatherFactory.$inject = ["$http"];
angular.module('displayApp').factory('weatherFactory', weatherFactory);
}());
Specific error is
Cannot read property 'getWeather' of undefined
at init (WeatherController.js:17)
What am I missing, or what am I doing wrong?
Any and all help is appreciated.
Thanks.
You are missing a few injections. You currently have:
WeatherController.$inject = ['$scope', 'weatherFactory'];
And your arguments are $scope, $log, $http, weatherFactory. Just add the missing injections:
WeatherController.$inject = ['$scope', '$log', '$http', 'weatherFactory'];
I wanna use multiple ( in this case, 2 ) $http.gets in my service !
As you know the simple form of using $http.get is this :
app.factory('MyService', function ($http, $q) {
return {
getData: function() {
return $http.get('myfile.json')
.then(function(response) {
return response.data;
});
}
};
});
Now I wanna use 2 files ( 2 $http.gets ) and compare them to each other ( with some for loops and etc that I can ... ) !
What can I do now ? :(
use $q.all.
Add $q to controller's dependencies, exemple
$scope.req1 = $http.get('myfile.json');
$scope.req2 = $http.get('myfile2.json');
$q.all([$scope.req1, $scope.req2]).then(function(data) {
// data is array of your files
if ( JSON.stringify(data[0]) === JSON.stringify(data[1])){
console.log('is equal');
}
});
It is an extension of Hajji Tarik's solution. I was able to derive from your comments that you were still not clear with what to code in where. So I have developed a sample application which will assist you for the same.
//--app.module.js--//
angular.module('notesApp', []);
//--app.service.js--//
angular.module('notesApp')
.factory('notesFactory', ['$http',
function($http) {
var notesService = {};
notesService.getData = function(url, method) {
return $http({
url: url,
method: method
});
}
return notesService;
}
]);
//--app.controller.js--//
angular.module('notesApp')
.controller('MainController', ['$scope', '$http', '$log', '$q', 'notesFactory',
function($scope, $http, $log, $q, notesFactory) {
$scope.data = {};
var data1 = notesFactory.getData('http://localhost:3000/api/notes/1', 'GET');
var data2 = notesFactory.getData('http://localhost:3000/api/notes/2', 'GET');
var combinedData = $q.all({
firstResponse: data1,
secondResponse: data2
});
combinedData.then(function(response) {
$log.log(response.firstResponse.data);
$log.log(response.secondResponse.data);
//Write your comparison code here for comparing json results.
}, function(error) {
$scope.data = error;
});
}
]);
<html ng-app='notesApp'>
<head>
<title>
Notes Application
</title>
</head>
<body>
<div ng-controller='MainController'>
</div>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js'></script>
<script src='app.module.js'></script>
<script src='app.controller.js'></script>
<script src='app.service.js'></script>
</body>
</html>
I have been trying to get data from a json file through service in AngularJS(1.5.3). I am unable to retrieve the data from json and display it in the view. I get blank values instead. Below is the code:
//Service
angularStoreApp.factory('dataService', ['$http', function ($http, $q) {
return {
getProducts: function () {
var promise = $http.get('/api/json/products.json')
.then(function successCallback(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
// invalid response
return "Invalid data";
}
}, function errorCallback(response) {
return "Invalid data";
})
return promise;
}
};
}]);
//Controller
/// <reference path="SearchController.js" />
angularStoreApp.controller('SearchCtrl', ['$scope', 'dataService', function ($scope, dataService) {
$scope.ProductItems = [];
dataService.getProducts()
.then(function (data) {
$scope.ProductItems = data;
});
}]);
<blockquote>
<h4 style="color: salmon">Welcome to the New Store
<br />
Please select the products you want and add them to your shopping cart.
<br />
When you are done, click the shopping cart icon to review your order and checkout.
<br />
</h4>
<div class="row">
<div class="col-sm-12" ng-repeat="ProductItem in ProductItems track by $index">
{{ProductItem.Name}}, {{ProductItem.Price}}
</div>
</div>
Update:
Below is the json data that I have.
[{
"itemName": "Notepad",
"itemPrice": 12,
"itemQuantity": 0
},
{
"itemName": "Pen",
"itemPrice": 8,
"itemQuantity": 0
},
{
"itemName": "Pencil",
"itemPrice": 5,
"itemQuantity": 0
}];
Could anyone help me out.
I think the problem is in your first line!
you should pass all the services as string:
angularStoreApp.factory('dataService', ['$http', '$q' function ($http, $q) {
In order to get the code snippet working, you need to
initialize the module in the js: var angularStoreApp = angular.module('storeapp', []);
add ng-app in the view
add ng-controller in the view (or use routing)
Forgetting to add $q to the dependencies is indeed a mistake, but it doesn't prevent your app from working, as long as you don't use $q.
Below is an adjusted, working code snippet. I simulated the http call by returning json wrapped in a promise. If it still doesn't work, the problem is the HTTP call, i.e. the part I commented out. Execute the call in the browser and verify that the correct JSON is returned.
var angularStoreApp = angular.module('storeapp', []);
//Service
angularStoreApp.factory('dataService', ['$http', '$q',
function($http, $q) {
return {
getProducts: function() {
//simulate promise with json:
return $q.when([{
'Name': 'name 1',
'Price': 1.23
}, {
'Name': 'name 2',
'Price': 4.56
}]);
//var promise = $http.get('/api/json/products.json')
// .then(function successCallback(response) {
// if (typeof response.data === 'object') {
// return response.data;
// } else {
// invalid response
// return "Invalid data";
// }
// }, function errorCallback(response) {
// return "Invalid data";
// })
// return promise;
}
};
}
]);
//Controller
/// <reference path="SearchController.js" />
angularStoreApp.controller('SearchCtrl', ['$scope', 'dataService',
function($scope, dataService) {
$scope.ProductItems = [];
dataService.getProducts()
.then(function(data) {
$scope.ProductItems = data;
});
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="storeapp" ng-controller="SearchCtrl">
<blockquote>
<h4 style="color: salmon">Welcome to the New Store
<br />
Please select the products you want and add them to your shopping cart.
<br />
When you are done, click the shopping cart icon to review your order and checkout.
<br />
</h4>
<div class="row">
<div class="col-sm-12" ng-repeat="ProductItem in ProductItems track by $index">
{{ProductItem.Name}}, {{ProductItem.Price}}
</div>
</div>
</div>
I've replicated your code in jsbin and it is working fine through I've changed the code for brevity.
The issue might be with below code as it looks for products.json in root folder not in your project folder.
$http.get('/api/json/products.json')
Try with removing '/' in the URL.
$http.get('api/json/products.json')
I found the answer after reading the following links
http://www.dwmkerr.com/promises-in-angularjs-the-definitive-guide/
http://bguiz.github.io/js-standards/angularjs/resolving-promises-for-a-controller/
The following is how I modified my code to get it working:
In the config routing section I used the resolve property for that route
var angularStoreApp = angular.module('AngularStore', ['ngRoute']);
angularStoreApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/products', {
templateUrl: '/Views/Store.html',
controller: 'SearchCtrl',
resolve: {
resolvedJSON: function (dataService) {
return dataService.getProducts();
}
}
})
.when('/product/:productName', {
templateUrl: '/Views/product.html',
controller: 'ProductCtrl'
})
.otherwise({
redirectTo: '/products'
});
}]);
Now I injected the resolvedJSON in my controller as follows
/// <reference path="SearchController.js" />
angularStoreApp.controller('SearchCtrl', ['$scope', 'resolvedJSON', function ($scope, resolvedJSON) {
$scope.ProductItems = [];
$scope.ProductItems = resolvedJSON;
}]);
And my service code as follows:
angularStoreApp.factory('dataService', ['$http', function ($http, $q) {
return {
getProducts: function () {
return $http.get('/api/json/products.json')
.then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
return "Invalid data";
})
}
};
following is my json data
[{
"itemName": "Notepad",
"itemPrice": 12,
"itemQuantity": 0
},
{
"itemName": "Pen",
"itemPrice": 8,
"itemQuantity": 0
},
{
"itemName": "Pencil",
"itemPrice": 5,
"itemQuantity": 0
}]
My view(Store.html) is something like this:
<div class="row">
<div class="col-sm-12" ng-repeat="ProductItem in ProductItems track by $index">
{{ProductItem.itemName}}, {{ProductItem.itemPrice}}
</div>
</div>
Hope this helps anyone facing a similar issue as mine. Thank you everyone who steered me to a better and simple answer.
u forgot the '$q' for minification
u should use the var deferred = $q.defer();// (I will add a full code)
example jsfiddle
angular.module('app', [])
.controller('ctrl', function(dataService, $scope) {
var vm = this;
$scope.ProductItems = [];
dataService.getProducts()
.then(function(data) {
$scope.ProductItems = data;
});
})
.factory('dataService', ['$http', '$q', function($http, $q) {
function getProducts() {
var deferred = $q.defer();
$http.get('https://httpbin.org/get')
.then(function successCallback(response) {
if (typeof response.data === 'object') {
// let say we get list of Products
deferred.resolve([{
id: 1,
name: 'Product1'
}, {
id: 2,
name: 'Product2'
}, {
id: 3,
name: 'Product3'
}]);
} else {
// invalid response
return "Invalid data";
}
}, function errorCallback(response) {
return deferred.reject("Invalid data");
})
return deferred.promise;
}
return {
getProducts: getProducts
};
}]);
I think one of the problems you have is already mentioned #Ahmad Mobaraki ,and another one is in your dataService, the promise object returned by $http.get('/api/json/products.json') is already consumed by then() function, so what you need to do is to create a new promise and return it.
Code example:
//service
angularStoreApp.factory('dataService', ['$http', '$q', function ($http, $q) {
return {
getProducts: function () {
var defered = $q.defer();
$http.get('/api/json/products.json')
.then(function successCallback(response) {
if (typeof response.data === 'object') {
defered.resolve(response.data);
} else {
// invalid response
defered.reject("Invalid data");
}
}, function errorCallback(response) {
defered.reject("Invalid data");
});
return defered.promise;
}
};
}]);
//Controller
angularStoreApp.controller('SearchCtrl', ['$scope', 'dataService', function ($scope, dataService) {
$scope.ProductItems = [];
dataService.getProducts()
.then(function (data) {
$scope.ProductItems = data;
});
}]);
hope this can help you :)
Here is my html code:
<div ng-controller="withAjaxCtrl">
<table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="row-border hover"></table>
</div>
Here is my controller:
(function () {
var manageBackOrdersController = function ($scope, $http, $routeParams) {
$http({
url: '/Profiles/firstJson',
method: "GET",
params: {}
}).success(function (data) {
var JSON = data;
$scope.data = JSON;
});
}
manageBackOrdersController.$inject = ['$scope', '$http', '$routeParams'];
angular.module('customersApp')
.controller('manageOrdersController', manageOrdersController);
angular.module('datatablesSampleApp', ['datatables'])
.controller('withAjaxCtrl', function ($scope, DTOptionsBuilder, DTColumnBuilder) {
$scope.dtOptions = DTOptionsBuilder.fromSource('scope.data')
.withPaginationType('full_numbers');
$scope.dtColumns = [
DTColumnBuilder.newColumn('Customer').withTitle('Customer')
];
});
}());
When I run my page I get an error saying "Error: [ng:areq] Argument 'withAjaxCtrl' is not a function, got undefined". My data is found stored in $scope.data.
Respectfully, Sameer's answer is incorrect. It took me two long arduoous days but I found the solution.
What you must keep in mind are 2 concerns:
Use DTOptionsBuilder.fromFnPromise, and
Have your promise inside your factory.
This is the correct solution:
'use strict';
WithResponsiveCtrl.$inject = ['DTOptionsBuilder', 'DTColumnBuilder', 'simpleFactory'];
angular.module('showcase.withResponsive', [])
.controller('WithResponsiveCtrl', WithResponsiveCtrl);
function WithResponsiveCtrl(DTOptionsBuilder, DTColumnBuilder, simpleFactory) {
var vm = this;
vm.dtOptions = DTOptionsBuilder.fromFnPromise(function() {
return simpleFactory.getData(); }).withPaginationType('full_numbers')
// Active Responsive plugin
.withOption('responsive', true);
vm.dtColumns = [
DTColumnBuilder.newColumn('id').withTitle('ID'),
DTColumnBuilder.newColumn('firstName').withTitle('First name'),
// .notVisible() does not work in this case. Use .withClass('none') instead
DTColumnBuilder.newColumn('lastName').withTitle('Last name').withClass('none')
]; }
simpleFactory.$inject = ['$http', '$q', '$log'];
angular.module('showcase.withResponsive').factory('simpleFactory', simpleFactory);
function simpleFactory($http, $q, $log) {
return {
getData: function () {
var deferred = $q.defer();
$http.get('api/data.json')
.success(function (data) {
deferred.resolve(data);
}).error(function (msg, code) {
deferred.reject(msg);
$log.error(msg, code);
});
return deferred.promise;
}
} };
var nameSpace = angular.module("MyTutorialApp", []);
nameSpace.controller("MainController", ['$scope', '$http',
function($scope, $http)
{
$http.get("../api/api.php?fxn=" + encodeURIComponent("getCategories") +
"&jsn=" + encodeURIComponent("{'code':'1'}"))
.success(function(response)
{
$scope.names = response;
});
$scope.myData = {};
nameSpace.controller("MainController", ['$scope', '$http',
$scope.myData.doClick = function($event, name, $scope, $http,$config)
{
alert(name);
var element = name;
console.log(element);
$http.get("../api/api.php?fxn=" + encodeURIComponent("getSubCategories") +
"&jsn=" + encodeURIComponent("{'code':'element'}"))
.success(function(response)
{
$scope.subCat = response;
});
}]);
}
]);
<!DOCTYPE html>
<head>
<title>Learning AngularJS</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="js/maincontroller.js"></script>
</head>
<body ng-app="MyTutorialApp" >
<div ng-controller="MainController">
<table class="table">
<tr class="row1" ng-repeat="list in names.category">
<td ng-click="myData.doClick($event,list.name)">{{ list.name }}</td>
</tr>
</table>
</div>
</body>
</html>
Hi, i m not able to make the second http request , It says get property undefined. I tried for quite along time, i am not able to spot what is going wrong. Kindly Help me. I am just starting to use angular.
To explain what I am trying to achieve , the first http request calls for the list of categories , the list is populated and after that on click of any of the category , the category is sent as the jsn for the second http request . And it fetch's the sub category
Check this
// Code goes here
var nameSpace = angular.module("MyTutorialApp", []);
nameSpace.factory('factoryRefrence', ['$http', '$q',
function($http, $q) {
return {
getCategories: function() {
var deferred = $q.defer();
$http.get("../api/api.php?fxn=" + encodeURIComponent("getCategories") +
"&jsn=" + encodeURIComponent("{'code':'1'}"))
.success(function(response) {
deferred.resolve(response);
});
return deferred.promise;
},
getsubCategories: function(element) {
var deferred = $q.defer();
$http.get("../api/api.php?fxn=" + encodeURIComponent("getSubCategories") +
"&jsn=" + encodeURIComponent({
'code': element
}))
.success(function(response) {
deferred.resolve(response);
});
return deferred.promise;
}
}
}
]);
nameSpace.controller("MainController", ['$scope', '$http', 'factoryRefrence',
function($scope, $http, factoryRefrence) {
factoryRefrence.getCategories().then(function(response) {
$scope.names = response;
});
$scope.myData = {};
$scope.myData.doClick = function(event, name) {
alert(name);
var element = name;
console.log(element);
factoryRefrence.getsubCategories().then(function(response) {
$scope.subCat = response;
});
}
}
]);
Demo
this is the way to communicate with functions in factory. if you setup like this it should work fine. and besides in your code you are defining controller twice which is not okay.