I not able to validate my input to the json data whenever i try to compare with json the else block only executed. pls help me to fix this issue.
<body ng-app="fileGetting" ng-controller="loadFile">
<label>Firstname:</label><input type="text" ng-model="placeFile.fname"><br>
<label>Lastname:</label><input type="text" ng-model="placeFile.lname"><br>
<button ng-click="fun()">Submit</button><br>
<div ng-repeat="x in placeFile">
<p>{{x.fname}}</p>
</div>
<script>
angular.module("fileGetting", [])
.controller("loadFile", function($scope, $http) {
$http.get("exam.json").then(function(response) {
$scope.placeFile = response.data.names;
var x = $scope.placeFile;
$scope.fun = function() {
angular.forEach(x, function(value, key) {
if ($scope.placeFile.fname == x.key && $scope.placeFile.lname == x.key)
{
alert("hi ram");
}
else
{
alert("this is incorrect");
}
});
}
});
});
</script>
This is the Json data:
{
"names":[
{
"fname":"Ram",
"lname":"Chandru"
},
{
"fname":"Chandran",
"lname":"Krishna"
},
{
"fname":"Jayanth",
"lname":"Jo"
}
]
}
Eventually i got an answer i would like to thanks Magnus and Simon.
<body ng-app="myApp" ng-controller="loadFile">
<label>Firstname:</label><input type="text" ng-model="current.fname"><br>
<label>Lastname:</label><input type="text" ng-model="current.lname"><br>
<button ng-click="fun()">Submit</button><br>
<script>
angular.module("myApp", [])
.controller("loadFile", function($scope, $http) {
$scope.current = {fname:"", lname:""};
$http.get("exam.json").then(function(response) {
$scope.placeFile = response.data.names;
$scope.fun=function(){
$scope.placeFile.forEach(function(itm) {
if ($scope.current.fname===itm.fname && $scope.current.lname === itm.lname ) {
alert("Hi Ram");
}
});
}
});
});
</script>
If i understand correctly what you are doing the following should work:
First change
<label>Firstname:</label><input type="text" ng-model="placeFile.fname"><br>
<label>Lastname:</label><input type="text" ng-model="placeFile.lname"><br>
to
<label>Firstname:</label><input type="text" ng-model="current.fname"><br>
<label>Lastname:</label><input type="text" ng-model="current.lname"><br>
code should be:
angular.module("myApp", [])
.controller("loadFile", function ($scope, $http) {
$scope.current = { "fname": "", "lname": "" };
$scope.placefile = [];
$http.get("exam.json").then(function (response) {
$scope.placeFile = response.data.names;
});
$scope.fun = function () {
$scope.placeFile.forEach(function (itm) {
if (itm.fname === $scope.current.fname
&& itm.lname === $scope.current.lname) {
alert("Hi Ram");
}
else {
alert("incorrect");
}
});
};
});
Regards
Magnus
Related
I am trying to activate a checkbox from a controller that lives in another controller. For example, I have a card named information technology under a separate controller and when I click this I want it to route to another page that has a checkbox for information technology from another controller and I want it checked as it renders the page.
The application architecture is very lengthy so I wont include any code base here. But I would like to know an approach I can take.
This is the controller where I want the logic to live and to mark a text box as checked (which lives on another controller).
angular
.controller("mycontroller", mycontroller);
mycontroller.$inject = [
"$scope"
];
// getting the getData() data
$scope.getData = function (data, type) {
console.log("whats this data about in getData(data) ", data)
$scope.query = data.name;
if (data.checked == undefined) {
data.checked = true;
}
}
Below: Is the controller where the checkbox controller lives
angular
.controller('supplierIntelligenceCtrl', function ($scope, $q, FetchData, dataStore, SharedService,
$document, $window, $state, $rootScope, $timeout, DataCache,
$filter, $interval, $localStorage, $http) {
$scope.getData = function (data, type) {
console.log("whats this data about in getData(data) ", data)
$scope.query = data.name;
if (data.checked == undefined) {
data.checked = true;
}
}
$scope.apply = function (type) {
$scope.select = false;
$scope.bigres = 0;
$scope.mobFil = 3;
$scope.applyFilter(type);
}
$scope.disableApply = false;
$scope.disableApply2 = false;
$scope.applyFilter = function (type) {
console.log("this is type ", type)
if (type == 'industries') {
$scope.filters.industries = $scope.industries.filter(function (e) {
console.log("this is e ", e.checked)
return e.checked;
}).map(function (f) {
console.log(" this is f >>>> ",
f)
return f.id
})
$scope.filters.countries = [];
if ($scope.countries != undefined) {
$scope.countries = $scope.countries.map(function (e) {
e.checked = false;
return e;
})
}
$scope.filters.cities = [];
if ($scope.cities != undefined) {
$scope.cities = $scope.cities.map(function (e) {
e.checked = false;
return e;
})
}
$scope.start = 0;
if ($scope.filters.industries.length > 0) {
$scope.callBackend();
$scope.disableApply2 = true;
FetchData.fetchDNBCountriesByIndustries('industries=' + $scope.filters.industries + '&size=').then(function (res) {
$scope.disableApply2 = false;
$scope.countries = res.data;
$scope.countriesPage += 10
}, function () {
$scope.disableApply2 = false;
});
} else {
$scope.callBackend();
}
}
if (type == 'countries') {
$scope.filters.countries = $scope.countries.filter(function (e) {
return e.checked;
}).map(function (f) {
return f.id;
})
$scope.filters.cities = [];
if ($scope.cities != undefined) {
$scope.cities = $scope.cities.map(function (e) {
e.checked = false;
return e;
})
}
$scope.start = 0;
if ($scope.filters.countries.length > 0) {
$scope.callBackend();
$scope.disableApply2 = true;
FetchData.fetchDNBCitiesByIndustriesAndCountries('industries=' + $scope.filters.industries + '&countries=' + $scope.filters.countries + '&size=').then(function (res) {
$scope.disableApply2 = false;
$scope.cities = res.data;
}, function () {
$scope.disableApply2 = false;
})
} else {
$scope.callBackend();
}
}
if (type == 'cities') {
$scope.filters.cities = $scope.cities.filter(function (e) {
return e.checked;
}).map(function (f) {
return f.id
})
$scope.start = 0;
$scope.callBackend();
}
if (type == 'classifications') {
$scope.filters.classifications = $scope.classifications.filter(function (e) {
return e.checked;
}).map(function (f) {
return f.statusCode;
})
$scope.start = 0;
$scope.callBackend();
}
}
}
Here is the HTML where the checkbox lives:
<div ng-repeat="data in industries ">
<input id="{{data.id}}in" type="checkbox" aria-invalid="false"
ng-model="data.checked"
ng-change="getData(data,'industry')">
<label for="{{data.id}}in">{{data.name}}</label>
</div>
Maybe Im missing the point here and perhaps am overlooking something. Im new to angularjs and need to implement this capability to route a button/card to another page that checks a checkbox filter.
Please - any advise would be great . :)
Here is an example of controllers sharing an array via a shared service injected by the dependency injector. Check the checkbox in one controller and it shows in the other.
angular.module('app', []);
angular.module('app')
.factory('dataService', [function () {
return {
data: [
{ prop: '1', checked: false },
{ prop: '2', checked: false },
{ prop: '3', checked: false },
{ prop: '4', checked: false }
]
};
}]);
angular.module('app')
.controller('controller1', ['dataService', function (dataService) {
this.data = dataService.data;
}]);
angular.module('app')
.controller('controller2', ['dataService', function (dataService) {
this.data = dataService.data;
}]);
angular.module('app')
.controller('controller3', ['dataService', function (dataService) {
this.toggleAll = () => {
dataService.data.forEach(item => item.checked = !item.checked)
};
}]);
[ng-controller] { display: inline-block; margin-right: 30px; vertical-align: top; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="controller1 as ctrl">
<strong>Controller 1</strong>
<div ng-repeat="item in ctrl.data">
<label>Item {{item.prop}} <input type="checkbox" ng-model="item.checked"></label>
</div>
</div>
<div ng-controller="controller2 as ctrl">
<strong>Controller 2</strong>
<div ng-repeat="item in ctrl.data">
<label>Item {{item.prop}} <input type="checkbox" ng-model="item.checked"></label>
</div>
</div>
<div ng-controller="controller3 as ctrl">
<strong>Controller 3</strong>
<div>
<button ng-click="ctrl.toggleAll()">Toggle all</button>
</div>
</div>
</div>
Put industries as a property on a shared service that you inject into both of the controllers by the dependency injector. Then one controller can bind it to it's view and the other one can change the checked properties on them.
Since you are talking about redirection and then checking a check box, you can try either of below options
Send selection 'information technology' in query string to redirected page and check the check box
If you own a back end server then put the value in cookie and read it in your angular js app
Hope this helps.
I am working on a note-taking app.
I want my app to delete all checked radios on clicking the 'Remove' link. An insight into the code:
HTML:
<p>[ <a href='#/home'>Cancel</a> | <a href='#/home/edit' ng-click='remove()'>Remove</a> ]</p>
<table border='0'>
<tbody>
<tr ng-repeat='note in notes'>
<td>
<input type='radio' ng-model='note.rmv'></input>
</td>
<td>{{note.text}}</td>
</tr>
</tbody>
</table>
Controller:
app.controller('editCtrl', ['$scope', 'notes', function($scope, notes) {
$scope.notes = notes.notes;
$scope.remove = function() {
for (var i = 0; i < $scope.notes.length; ++i) {
if ($scope.notes[i].rmv) {
delete $scope.notes[i];
notes.getLost($scope.notes[i]._id);
}
}
};
}]);
Factory:
app.factory('notes', ['$http', function($http) {
var t = {
notes: []
};
t.getLost = function(id) {
return $http.delete('/home/edit').success(function(data) {
return t.getAll();
});
};
return t;
};
What might be doing wrong here?
Well, there are a lot of mistakes in your code, I think you should refactor your code. Also there's no necessity of delete the item in Javascript, you can delegate it all to your back-end since you already have the function to getAll objects.
See the code below to take it as example:
(function() {
angular
.module('app', [])
.controller('editCtrl', editCtrl)
.factory('notes', notes);
editCtrl.$inject = ['$scope', 'notes'];
function editCtrl($scope, notes) {
getAll(); // <- initialization of notes
$scope.remove = remove;
function getSuccess(response) {
console.log('success');
}
function getError(response) {
console.log('error');
}
function remove() {
for (var i = 0; i < $scope.notes.length; ++i) {
if ($scope.notes[i].rmv) {
notes.getLost($scope.notes[i]._id)
.then(getSuccess)
.catch(getError);
}
}
fetchData();
}
function fetchData() {
notes.getAll()
.then(function(response) {
$scope.notes = response.data;
})
.catch(function(response) {
console.log('error');
});
}
}
notes.$inject = ['$http'];
function notes($http) {
var factory = {
getAll: getAll,
getLost: getLost
};
return factory;
function getAll() {
return $http.get('url_to_fetch');
}
function getLost(id) {
// It should only return the promise, not more than that
return $http.delete('/home/edit/' + id); // <- is this URL correct?
}
}
})();
You have a typo:
if($notes.notes[i].rmv) {
Should be:
if($scope.notes[i].rmv) {
I am trying to do a http post into database using AngularJS. My code doesn't shows any error, but my database is not being updated and I can't figure it out why. Here is my code:
//topic-service.js
(function() {
'use strict';
angular.module('topic').factory('topicService', topicServiceFunction);
topicServiceFunction.$inject = [ '$http', '$q' ];
function topicServiceFunction($http, $q) {
var topicService = {
getTopics : getTopics
}
return topicService;
function getTopics(obj) {
console.log('-->topicServiceFunction');
console.log(obj.name);
var deferred = $q.defer();
return $http.post('http://localhost:8080/restapp/api/topic',
JSON.stringify(obj)).then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
return deferred.reject(response.data);
}
}, function(response) {
return deferred.reject(response.data);
});
}
}
}())
//topic-controller.js
(function() {
'use strict';
angular.module('topic').controller('topicController',
topicControllerFunction);
topicControllerFunction.$inject = [ '$scope', 'topicService' ];
function topicControllerFunction($scope, topicService) {
$scope.getTopics = getTopics;
function getTopics(topicId,name,description,categId,userId) {
console.log('-->topictrlFunction');
$scope.topics = [];
var obj={
id:$scope.topicId,
name:$scope.name,
description:$scope.description,
id_category:$scope.categId,
user_id:$scope.userId
}
var promise = topicService.getTopics(obj);
promise.then(function(data) {
if (data != undefined && data != null) {
$scope.topics = data;
} else {
$scope.topics = undefined;
}
}, function(error) {
console.log('error=' + error);
$scope.topics = undefined;
})
topicService.getTopics(obj);
$scope.topics = topicService.getTopics(obj);
}
}
}())
//topic.html
<!DOCTYPE html>
<html lang="en" ng-app="myTopics">
<head>
<meta charset="UTF-8">
<script src="../../../bower_components/angular/angular.js"></script>
<script src="app.js"></script>
<script src="topics/module/topic-module.js"></script>
<script src="topics/controller/topic-controller.js"></script>
<script src="topics/service/topic-service.js"></script>
<title>Topics</title>
</head>
<body>
<div ng-controller="topicController">
<div ng-controller="topicController">
<p>
Topic id: <input type="text" ng-model="topicId">
</p>
<p>
Name: <input type="text" ng-model="name">
</p>
<p>
Description: <input type="text" ng-model="description">
</p>
<p>
Id category: <input type="text" ng-model="categId">
</p>
<p>
User id: <input type="text" ng-model="userId">
</p>
<button ng-click="getTopics(topicId,name,description,categId,userId)">Add
topic</button>
<ul ng-repeat="topic in topics">
<li>{{topic.id}} --{{topic.name}} -- {{topic.description}} --
{{topic.id_category}}--{{topic.user_id}}</li>
</ul>
</div>
</body>
</html>
In your service you use $q but return $http promise, that's counter productive, just return deferred promise:
function getTopics(obj) {
console.log('-->topicServiceFunction');
console.log(obj.name);
var deferred = $q.defer();
var data = JSON.stringify(obj)
$http.post('http://localhost:8080/restapp/api/topic', data)
.then(function(response) {
if (typeof response.data === 'object') {
deferred.resolve(response.data);
} else {
deferred.reject(response.data);
}
})
.catch(function(response) {
return deferred.reject(response.data);
});
return deferred.promise;
}
If it still doesn't work you should try to send urlencoded data and not json :
for this just add this header in your request : headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
and encode data with $httpParamSerializerJQLike service. (Inject it in your service)
function getTopics(obj) {
console.log('-->topicServiceFunction');
console.log(obj.name);
var deferred = $q.defer();
var data = $httpParamSerializerJQLike(obj);
var config = {
headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
};
$http.post('http://localhost:8080/restapp/api/topic', data, config)
.then(function(response) {
if (typeof response.data === 'object') {
deferred.resolve(response.data);
} else {
deferred.reject(response.data);
}
})
.catch(function(response) {
return deferred.reject(response.data);
});
return deferred.promise;
}
I try to do my first angularjs application, but i have a problem. I have 2 controllers (and i would like to keep 2): the first to list items, the second to edit or create an item.
When I save an item, or create a new item, i can't edit another or create another, after to do one action the form can't load or save... The problem seems to be this line :
$scope.editPlace = {};
But I don't understand why...
DEMO :
http://jsfiddle.net/cxL7qmke/
HTML:
<div ng-app="mapApp">
<div ng-controller="EditPlaceCtrl">
<form name="editPlaceForm">
<fieldset>
<label for="title">Title:</label>
<input id="title" type="text" ng-model="editPlace.title">
<input type="hidden" ng-model="editPlace.id" />
<button type="submit" ng-click="savePlace()">Save</button>
</fieldset>
</form>
</div>
<section ng-controller="PlaceCtrl">
<ul>
<li ng-repeat="place in places">
<label>{{place.title}} edit</label>
</li>
</ul>
</section>
</div>
JS :
var mapApp = angular.module('mapApp', []);
mapApp.controller('PlaceCtrl', function ($scope, $rootScope, placeService) {
$scope.places = placeService.getAll();
$scope.edit = function (id) {
$rootScope.editPlace = angular.copy(placeService.get(id));
}
});
mapApp.controller('EditPlaceCtrl', function ($scope, placeService) {
$scope.savePlace = function () {
placeService.save($scope.editPlace);
$scope.editPlace = {};
}
});
mapApp.service('placeService', function ($filter) {
var uid = 3;
var places = [
{ id: 1, title: 'Item1', lat: 43.123, lng: -89.123 },
{ id: 2, title: 'Item2', lat: 43.321, lng: -89.321 }
];
this.getAll = function () {
return places;
}
this.get = function (id) {
var place, i;
for (i in places) {
if (places[i].id === id) {
return places[i];
}
}
return false;
};
this.save = function (place) {
if (place.id == null) {
place.id = this.uid++;
places.push(place);
} else {
for (i in places) {
if (places[i].id == place.id) {
places[i] = place;
}
}
}
};
});
I've made few changes and seems to work for me please see here
http://jsfiddle.net/m9bevovy/
in your service I've added
this.newPlace = {};
this.setNew = function (id) {
this.newPlace = this.get(id);
};
and your controllers :
mapApp.controller('PlaceCtrl', function ($scope, $rootScope, placeService) {
$scope.places = placeService.getAll();
$scope.edit = function (id) {
placeService.setNew(id);
}
});
mapApp.controller('EditPlaceCtrl', function ($scope, placeService) {
$scope.placeService = placeService;
$scope.savePlace = function () {
placeService.save($scope.placeService.newPlace);
$scope.placeService.newPlace = {};
}
});
You are using both $scope and $rootScope to hold the reference to editPlace.
If you want to use the $rootScope, use this in your savePlace function:
$rootScope.editPlace = {};
Instead of:
$scope.editPlace = {};
Here`s the working fiddle
my database has two tables one for "Customers" and another for "Tripsheets".
I would like to call the routeParams data of Customers into Tripsheets.
I tried something like this, but it does'nt work
HTML
<div class="row mini-stat" ng-controller="TripsheetCtrl1" >
<div class="col-md-4">
<div class="input-group m-bot15">
<span class="input-group-addon btn-white"><i class="fa fa-user"></i></span>
<input ng-model="tripsheet.tripsheet_num" type="text" class="form-control input-lg" >
</div>
</div>
JS
var urltd = 'http://localhost/tripsheets';
app.factory('tripsheetFactoryd', function ($http) {
return {
getTripsheetsd: function () {
return $http.get(urltd + '/all');
},
addTripsheetd: function (tripsheet) {
return $http.post(urltd, tripsheet );
},
deleteTripsheetd: function (tripsheet) {
return $http.delete(urltd + '?id=' + tripsheet.id);
},
updateTripsheetd: function (tripsheet) {
return $http.put(urltd + '?id=' + tripsheet.id, tripsheet);
}
};
});
var url = 'http://localhost/customers';
app.factory('customerFactory', function ($http) {
return {
getCustomers: function () {
return $http.get(url + '/all');
},
addCustomer: function (customer) {
return $http.post(url, customer);
},
deleteCustomer: function (customer) {
return $http.delete(url + '?id=' + customer.id);
},
updateCustomer: function (customer) {
return $http.put(url + '?id=' + customer.id, customer);
}
};
});
app.controller('TripsheetCtrl1', function ($scope, tripsheetFactoryd, customerFactory, $routeParams) {
$scope.tripsheets = [];
tripsheetFactoryd.getTripsheetsd().then(function(data){
$scope.tripsheets = data.data;
$scope.tripsheet = {
tripsheet_num: "{{customers[whichItem].name}}"
};
$http.get(url + '/all').success(function(data) {
$scope.customers = data;
$scope.whichItem = $routeParams.itemId;
if ($routeParams.itemId > 0) {
$scope.prevItem = Number($routeParams.itemId)-1;
} else {
$scope.prevItem = $scope.customers.length-1;
}
if ($routeParams.itemId < $scope.customers.length-1) {
$scope.nextItem = Number($routeParams.itemId)+1;
} else {
$scope.nextItem = 0;
}
});
});
});
Since you're making the calls in the same controller TripsheetCtrl1 you will be sharing the same $scope...so first populate $scope.customers and $scope.whichItem by calling the $http.get and then use those values in your getTripsheetsd().
app.controller('TripsheetCtrl1', function ($scope, tripsheetFactoryd, customerFactory, $routeParams) {
$scope.tripsheets = [];
customerFactory.getCustomers().success(function(data) {
$scope.customers = data;
$scope.whichItem = $routeParams.itemId;
$scope.tripsheet = {
tripsheet_num: $scope.customers[$scope.whichItem].name;
};
if ($routeParams.itemId > 0) {
$scope.prevItem = Number($routeParams.itemId)-1;
} else {
$scope.prevItem = $scope.customers.length-1;
}
if ($routeParams.itemId < $scope.customers.length-1) {
$scope.nextItem = Number($routeParams.itemId)+1;
} else {
$scope.nextItem = 0;
}
});
tripsheetFactoryd.getTripsheetsd().then(function(data){
$scope.tripsheets = data.data;
});
});