how to check textbox isEmpty in angularJs Factory? - html

how to check textbox isEmpty in angularjs Factory?
My HTML Source is
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<input type="text" ng-model="test">
</div>
</body>
</html>

angular.module('myApp', [])
.controller('customersCtrl', function($scope){
$scope.changed = function(){
if(!$scope.test){
$scope.msg = 'empty';
} else {
$scope.msg = 'not empty';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
<input type="text" ng-model="test" ng-change="changed()"/>
{{ test }} | {{ msg }}
</div>

var customersCtrl = function($scope,Validate){
var isEmpty = Validate.isEmpty($scope.test);
$scope.Validation = Validate;
if(isEmpty){
console.info('Textbox is empty');
}else{
console.info('Textbox is not empty');
}
};
angular.module('myApp').controller('customersCtrl', customersCtrl);
var Validate = function() {
var factory = {};
factory.isEmpty = function(val){
var result = false;
if(!val){
result = true;
}
return result;
};
return factory;
};
angular.module('myApp').factory('Validate', Validate);
Here is the Plunker according to your requirement.

In your controller, you can check the model value at any point in time. Like
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
if($scope.test == ""){
// textbox is empty, do your stuff here
}
});

additional trick !
you can check it on angular expression . see this below to example !
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
$scope.test = "";
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<input type="text" ng-model="test">
<span ng-show="test.length == 0">
is empty </span>
</div>
</body>
</html>
hope !

Related

Not getting data by using ngDrive module by pinoyyid

<html>
<body ng-app="MyApp">
<div ng-controller="MainCtrl as vm">
<li ng-repeat="file in vm.filesArray">{{file.title}}</li>
</div>
<script src="https://apis.google.com/js/auth.js" type="text/javascript"></script>
<script src="../bower_components/angular/angular.min.js"></script>
<script src="../bower_components/ngDrive/build/module.js"></script>
<script>
var myApp = angular.module('MyApp', ['ngm.ngDrive']);
angular.module('ngm.ngDrive')
.provider('OauthService', ngDrive.Config)
.config(function (OauthServiceProvider) {
OauthServiceProvider.setScopes('https://www.googleapis.com/auth/drive.file');
OauthServiceProvider.setClientID('10503878599-98uqrqmgq2f3kc1sbr13l6rma20ue7l0.apps.googleusercontent.com');
});
var MainCtrl = (function () {
function MainCtrl(DriveService) {
this.filesArray = DriveService.files.list({
q: 'trashed = false',
maxResults: 10,
fields: 'items/title'
}, true).data;
}
MainCtrl.$inject = ['DriveService'];
return MainCtrl;
})();
angular.module('MyApp').controller('MainCtrl', MainCtrl);
</script>
</body>
</html>
I am using ngDrive by pinoyyid .
This is my index.html .
I have provided a valid client ID.
It returns an empty array in files array.
Please suggest any solution

how to store the JSON from directive to use it on next HTML page through angular

I have a requirement that i need to read a excel file from any location and to render the data of the excel on the next html page.
I was able to render the excel data with multiple sheets on the same page but now I need to select the file on first page and render its data on the next html page.
Like this:
And on the next screen need to show excel data:
Here in the Sheet Name i need to provide the sheet names from excel and on selecting any sheet name that sheet data need to be loaded in the grid.
I have used two divs to divide the page vertically in two columns.
I was able to achieve this functionality on a single page but now I need to divide this code in multiple pages.
This is the plunker of the work done:
http://plnkr.co/edit/xHEtxtzKrEiKDTrqlafC?p=preview
This is my js code:
angular.module('app', ['ui.grid'])
.controller('MainCtrl', ['$scope', function($scope) {
var vm = this;
vm.gridOptions = {};
vm.reset = reset;
vm.selectedSheet = '';
vm.sheetIndex = 0;
function reset() {
vm.gridOptions.data = [];
vm.gridOptions.columnDefs = [];
vm.selectedSheet = '';
vm.sheetIndex = 0;
}
vm.readSheet = function() {
var workbook = XLSX.read(vm.data, {
type: 'binary'
});
var headerNames = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[vm.sheetIndex]], {
header: 1
})[0];
vm.sheetNames = workbook.SheetNames;
var data = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[vm.sheetIndex]]);
vm.gridOptions.columnDefs = [];
headerNames.forEach(function(h) {
vm.gridOptions.columnDefs.push({
field: h
});
});
vm.gridOptions.data = data;
};
vm.onLoadData = function(data) {
vm.data = vm.data || data;
vm.readSheet();
};
vm.sheetChange = function() {
vm.sheetIndex = vm.sheetNames.indexOf(vm.selectedSheet);
vm.readSheet();
};
}])
.directive("fileread", [function() {
return {
scope: {
onLoadData: '&'
},
link: function($scope, $elm, $attrs) {
$elm.on('change', function(changeEvent) {
var reader = new FileReader();
reader.onload = function(evt) {
$scope.$apply(function() {
$scope.onLoadData({
data: evt.target.result
});
$elm.val(null);
});
};
reader.readAsBinaryString(changeEvent.target.files[0]);
});
}
}
}]);
HTML code:
<!DOCTYPE html>
<html ng-app="app">
<head>
<link data-require="bootstrap-css#*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.js"></script>
<script src="https://cdn.rawgit.com/SheetJS/js-xlsx/v0.8.0/dist/xlsx.full.min.js"></script>
<script src="https://cdn.rawgit.com/SheetJS/js-xlsx/v0.8.0/dist/ods.js"></script>
<script src="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.22/ui-grid.min.js"></script>
<link rel="stylesheet" href="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.22/ui-grid.min.css" />
<link rel="stylesheet" href="main.css" type="text/css" />
</head>
<body>
<div ng-controller="MainCtrl as vm">
<button type="button" class="btn btn-success" ng-click="vm.reset()">Reset Grid</button>
<br />
<br />
<div id="grid1" ui-grid="vm.gridOptions" class="grid">
<div class="grid-msg-overlay" ng-show="!vm.gridOptions.data.length">
<div class="msg">
<div class="center">
<span class="muted">Select Spreadsheet File</span>
<br />
<input type="file" accept=".xls,.xlsx,.ods" multiple="true" fileread="" on-load-data="vm.onLoadData(data)"/>
</div>
</div>
</div>
<div>
<select ng-model="vm.selectedSheet" ng-options="names as names for names in vm.sheetNames"
ng-change="vm.sheetChange()"></select>
{{vm.selectedSheet}}
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
I think i need to store this JSON somewhere, so that it can be used later in different pages.
Should I use service to achieve this functionality or any other approach need to be used please suggest.
I hope this might help!
You can just store the Json data in to any rootScope variable to use in another controllers.
For Example:
You have the following code;
vm.readSheet = function() {
var workbook = XLSX.read(vm.data, {
type: 'binary'
});
var headerNames = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[vm.sheetIndex]], {
header: 1
})[0];
vm.sheetNames = workbook.SheetNames;
var data = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[vm.sheetIndex]]);
vm.gridOptions.columnDefs = [];
headerNames.forEach(function(h) {
vm.gridOptions.columnDefs.push({
field: h
});
});
vm.gridOptions.data = data;
};
in here
vm.gridOptions.data = data;
you can set and store data for later usage as an JSON Array;
$rootScope.gridOptionsData = data;

Not able to delete in repeat method in AngularJS

'Remove Choice' is not working. Here are two functions addNewChoice and removeChoice. The addNewChoice is working however removeChoice is not working. I don't know how to solve it. Here my code is below:
<?php $obj = 1;?>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js">
</script>
<script type="text/javascript">
var app = angular.module('shanidkvApp', []);
app.controller('MainCtrl', function($scope)
{
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function()
{
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function(index)
{
var lastItem = $scope.choices.length-1;
$scope.choices.splice(index,1);
};
});
</script>
<%--here is my html --%>
<div class="btn btn-primary" ng-show="$last" ng-click="removeChoice()">Remove</div>
If all you want to do is remove last item in array you can simply use Array.prototype.pop()
$scope.removeChoice = function(){
$scope.choices.pop();
};
Seems like you should be using lastItem to delete and remove index parameter
$scope.removeChoice = function()
{
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem,1);
};
You didn't pass index in your removeChoice function in ng-click. You need to pass index of item in this function -
<div class="btn btn-primary" ng-show="$last" ng-click="removeChoice(index)">Remove</div>
You can get index from ng-repeat loop.
OR if you want to remove alway last item then you shouldn't need to pass index key in function. But you need to change in you function as below -
$scope.removeChoice = function(index)
{
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem,1);
};
var app = angular.module('shanidkvApp', []);
app.controller('MainCtrl', function($scope)
{
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function()
{
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function()
{
console.log($scope.choices);
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem,1);
console.log($scope.choices);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--here is my html -->
<body ng-app="shanidkvApp" ng-controller="MainCtrl">
<div class="btn btn-primary" ng-click="removeChoice()">Remove</div>
<div class="btn btn-primary" ng-click="addNewChoice()">Add</div>
<p></p>
</body>

Accessing Controller variable in ng-repeat in AngularJS

I am pretty new to web development and I have been working on a small project.
This is what I am trying to achieve. I have a badly nested JSON data for 10 products. This is the data I am using.
I have a "View More" button for each product for its specifications. The specifications can be accessed using the index as such "products[index].ProductInfo.p_product_specs.Value". When I click on the "view more" button, I am routing to a different page viewmore.html. In the viewmore.html, I have this html code
<div ng-controller='mainController'>
<div class="viewMore">
<ul ng-repeat="spec in products[id].ProductInfo.p_product_specs.Value">
{{ spec.Key }} : {{ spec.Value}}
</ul>
</div>
</div>
I have a function in the controller which return me the index of that product in the array "products" as soon as I click on the "View More" button.
$scope.viewmorefn = function(){
var self = this;
$scope.id = (function() {
//some code which returns index, console.log gives correct results.
return index;
}
)();
}
But when I try to use "id" in the ng-repeat (in viewmore.html), it just doesn't work. Is there any way I can make "id" accessible in my viewmore.html page? Any help will be greatly appreciated, I have already given this 2 days. Thanks.
EDIT : #uowzd01 : I am not sure if the data is being lost. The controller has this:
$http.get(url)
.success(function (result) {
$scope.products = result.ProductsList;
})
.error( function (data, status) {
console.log("Error retrieving data");
});
And in the viewmore.html I am able to interpolate "{{ products }}" and {{ products[0].ProductInfo.p_product_specs.Value }} and also the data of other objects if I specify the index explicitly.
EDIT 2: Complete code
HTML : First Page : product_list_page.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="assets/css/reset.css" />
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script src="https://code.angularjs.org/1.4.0/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.0/angular-route.min.js"></script>
<script src="app.js"></script>
<div class="main">
<div ng-view></div>
</div>
</body>
</html>
home.html
<div ng-controller='mainController'>
<div class="showProduct">
<div ng-show="isShow" ng-mouseenter="isShow=true">
<show-repeat></show-repeat>
</div>
</div>
<div class="eproducts" ng-repeat="product in products">
<div class="fixed-size-square" ng-mouseenter="hoverIn()">
<show-products></show-products>
</div>
</div>
</div>
viewmore.html
<div>
<div class="viewMore">
<ul ng-repeat="spec in products[selfId].ProductInfo.p_product_specs.Value">
<li> {{ spec.Key }} : {{ spec.Value}} </li>
</ul>
</div>
</div>
JavaScript code :
var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('mainController', ['$scope', '$window', '$filter', '$http', function($scope, $window, $filter, $http){
$http.get('data.txt')
.success(function (result) {
$scope.products = result.ProductsList;
})
.error( function (data, status) {
console.log("Error retrieving data");
});
$scope.hoverIn = function() {
$scope.isShow = true;
$scope.pr = this;
$scope.price = this.product.ProductInfo.p_product_price;
}
$scope.hoverOut = function() {
$scope.isShow = false;
}
$scope.returnPrice = function() {
$window.alert('The price is $' + $scope.price);
}
$scope.viewmorefn = function(){
var self = this;
$scope.selfId = (function() {
var count = 0;
var str1 = self.product.ProductInfo.Brand + self.product.ProductInfo.p_product_description;
for ( var i = 0 ; i < $scope.products.length ; i++)
{
var str2 = $scope.products[i].ProductInfo.Brand + $scope.products[i].ProductInfo.p_product_description;
if(str1 === str2)
break;
count = count + 1;
}
return count;
}
)();
console.log('id is : ' +$scope.selfId);
}
}]);
myApp.directive("showRepeat", function(){
return {
template : '<img class="lgImage" src="{{ pr.product.imageURLs.lg }}"> <br / > <div class="descText"> {{ pr.product.ProductInfo.Brand }} {{ pr.product.ProductInfo.p_product_description }} <br /> <div class="divClass"> <ul class="descList" ng-repeat="spec in pr.product.ProductInfo.p_product_specs.Value | newFilter"> <li> {{ spec.Key }} </li> </ul> </div> </div> <span class="priceText"> {{ product.ProductInfo.p_product_price | currency }} <br /> </span> <button id="cartBtn" ng-click="returnPrice()">Add to Cart</button> <br /> <div class="priceTop">{{ pr.product.ProductInfo.p_product_price | currency }} </div>'
}
});
myApp.directive("showProducts", function(){
return {
template : '<div class="prdList"><br /><img class="showprdimg" src="{{ product.imageURLs.sm }}"><br /><br/> <div class="spanText">{{ product.ProductInfo.Brand }} {{ product.ProductInfo.p_product_description }} </div> <br /><br/> <div class="priceText">{{ product.ProductInfo.p_product_price | currency }} </div><br/>"<button id="viewMoreBtn" ng-click="viewmorefn()">View More</button></div>'
}
});
myApp.filter('newFilter', function(){
return function(newSpec) {
var out = [];
angular.forEach(newSpec, function (newSpec) {
if((newSpec.Key === 'ENERGY STAR Qualified') && (newSpec.Value ==='Yes')) {
out.push(newSpec);
}
});
return out;
}
});
myApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'home.html',
controller : 'mainController'
})
// route for the view more page
.when('/viewmore', {
templateUrl : 'viewmore.html',
controller : 'mainController'
})
});
Plunker Demo
First, to clear some of the dust - though it is not the specific problem, you are instantiating the same controller numerous times - in your HTML and ngRoute. Pick one, not both. I got rid of the ng-controller directives in your HTML, so it just uses ngRoute now. However, because you are calling the same controller for both views, the controller is losing it's values because you are getting a new instance of the controller. It is also fetching the same data twice. While it technically is working, it's really bad JavaScript. You should look at ui-router and do some nested views and instantiate the controller one time and fetch the data one time.
To get it working, I essentially created a service to store the index value in:
myApp.factory('theIndex', function() {
return {
val: ''
}
})
When the controller loads, it pulls whatever value is stored in the service, and when you click the View More button, it stores the index value in the service.
myApp.controller('mainController', ['$scope', '$window', '$filter', '$http', 'theIndex', function($scope, $window, $filter, $http, theIndex){
$scope.selfId = theIndex.val; // get whatever index value is stored, if any
//... buncha stuff
$scope.viewmorefn = function(){
var self = this;
$scope.selfId = (function() {
var count = 0;
var str1 = self.product.ProductInfo.Brand + self.product.ProductInfo.p_product_description;
for ( var i = 0 ; i < $scope.products.length ; i++)
{
var str2 = $scope.products[i].ProductInfo.Brand + $scope.products[i].ProductInfo.p_product_description;
if(str1 === str2)
break;
count = count + 1;
}
return count;
}
)();
theIndex.val = $scope.selfId // set the index value here
console.log('id is : ' +$scope.selfId);
}
}]);
The plunker provided is updated, using all your supplied code. Don't forget to inject the new service into your controller. This should get you up and running, though as I said before, it's pretty ugly.

I can't acquire JSON data AngularJS

I want to get THE MOVIE REVIEWS API by The New York Times. I tried it using AngularJS but I was not provided.Can someone help me?
var app = angular.module('movieApp', []);
app.controller('movieController',
function movieController($scope, $http) {
$scope.fetchReviews = function() {
var api = 'http://api.nytimes.com/svc/movies/v2/reviews/all.jsonp?&offset=20&order=by-opening-date&api-key=XXX MY KEY XXX&responce-format=.jsonp&callback=JSON_CALLBACK';
$http.jsonp(api).success(function(data){
$scope.results = data.results;
});
}
});
HTML
<!DOCTYPE html>
<html lang="en" ng-app="movieApp">
<head>
<meta charset="UTF-8">
<title>Movie Review</title>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
<div ng-controller="movieController">
<ul class="review-cards">
<li ng-repeat="item in results">
<h2>{{item.display_title}}</h2>
<p>{{item.summary_short}}</p>
</li>
</ul>
</div>
</body>
</html>
You have to handle that event to some element or just call it in your controller.
var app = angular.module('movieApp', []);
app.controller('movieController',
function movieController($scope, $http) {
// define default value
$scope.results = [];
$scope.fetchReviews = function() {
var api = 'http://api.nytimes.com/svc/movies/v2/reviews/all.jsonp?&offset=20&order=by-opening-date&api-key=XXX MY KEY XXX&responce-format=.jsonp&callback=JSON_CALLBACK';
$http.jsonp(api).success(function(data){
$scope.results = data.results;
});
}
// call that event
$scope.fetchReviews();
});
Try it.
app.controller('movieController', function ($scope, $http) {
$scope.fetchReviews = function() {
var api = 'http://api.nytimes.com/svc/movies/v2/reviews/all.jsonp?&offset=20&order=by-opening-date&api-key=XXX MY KEY XXX&responce-format=.jsonp&callback=JSON_CALLBACK';
$http.jsonp(api).success(function(data){
$scope.results = data.results;
});
}
$scope.fetchReviews();
});
check like this