In the following script, I am able to get the first letter of string using anularJS.
var app = angular.module('myapp',[]);
app.controller('myCtrl',function($scope) {
$scope.myString = "kashif Riaz";
$scope.slicedString = $scope.myString.slice(0,1);
});
<div ng-app="myapp" ng-controller="myCtrl">
{{slicedString}}
</div>
But Actually my data is coming from database , and here i am unable to get the first letter of string ( which are contact Names).
here is an example of my approach.
app.controller("myCtrl",function($scope,$http) {
$http.post(
"names.php",
{'id':$scope.id}
).then(function(response) {
$scope.names = response.data;
$scope.fLetter = $scope.names.list.slice(0,1);
})
});
In the Last line of above code , ($scope.names.list.slice(0,1) , the list is a name of column in mysql table.
I have got a solution of my own question. that how to get first letter of a string by using a custom filter
var app = angular.module("myapp",[]);
app.filter('myFormat', function() {
return function(x) {
return x.slice(0,1);
};
});
app.controller("ctrl",function($scope,$http) {
$http.post(
"practicephp.php",
{'email':'kashfi#gmail.com','category':'mobileNumbers'}
).then(function(response) {
$scope.lists = response.data;
});
});
<ul ng-repeat= "x in lists">
<li>{{x.list_name | myFormat}}</li>
</ul>
Thank you for people who participate in my question to help me
Related
I am trying to display the data to my view but $scope.plan outputs {}. I am thinking that it would output the fetched data from the initGetEdit function, console.log() inside the $http.post outputs expected data.
controller.js
var id = $stateParams.id;
$scope.plan = {}
$scope.initGetEdit = function(){
var data = { id : id }
$http.post("someUrl", data).then(function(res){
$scope.plan = res.data;
console.log($scope.plan); //----> logs expected data
})
}
$scope.initGetEdit();
console.log($scope.plan); //----> logs {}
In my view I have something like this.
view
<input ng-model="plan.something" type="text" />
UPDATE
First thank you for those answers provided and the comments, appreciated it. It gives me an insight. I solved my issue by removing the initGetEdit function and staying with just the http.post.
Try keeping the second console in watch.
$scope.$watch('plan',function(){
console.log($scope.plan);
});
At first, you declare a variable $scope.plan = {} after that in http call of your $scope.initGetEdit function its empty object after the function http is an async call your object may be filled based on the response. until that it will be an empty object.
#Ujjwala Bollam mention in answer to print it in the console.
var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope,$http){
//var id = $stateParams.id;
var id=1;
$scope.plan = {}
$scope.initGetEdit = function(){
var data = { id : id }
//$http.post("http://someurl", data).then(function(res){
$scope.plan ={id:1,something:"hai this is response data"};
console.log($scope.plan); //----> logs expected data
//})
}
$scope.initGetEdit();
console.log($scope.plan); //----> logs {}
});
<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/1.11.1/jquery.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">
<input ng-model="plan.something" type="text" />
</div>
I'm using Angular and WebSQL in a Cordova project, and I've started a new list controller that will list the results of a table from the WebSQL database.
I have a sqlSvc that queries the database like so:
service.upc = function(newUpc) {
var deferred = $q.defer();
var resolveResults = function (tx, results) {
deferred.resolve(results.rows);
}
var selectUpcs = function() {
var queryString = "SELECT * FROM UPC";
service.db.transaction(function (tx) {
tx.executeSql(queryString, [], resolveResults, rejectWithError);
});
}
deferUntilInit(function () {
if (newUpc) {
insertOrReplaceAndSelect(newUpc); //omitted
} else {
selectUpcs();
}
});
return deferred.promise;
}
All the controller does is this:
var listCtrl = function($scope, sqlSvc) {
sqlSvc.upc().then(function(result) {
$scope.list = result;
});
}
angular.module("RDb").controller("listCtrl", ["$scope", "sqlSvc", listCtrl]);
And it's binding to a simple UI view template:
<div id="scanList">
<ul class="list-unstyled">
<li ng-repeat="scan in list">
<div>{{scan.upc}} ({{scan.datetime}})</div>
</li>
</ul>
</div>
This is giving me the 10 $digest iterations reached error, and it seems to be caused by the way WebSQL is return its results. The error goes away if I deep copy the data, changing resolveResults to:
var data = JSON.parse(JSON.stringify(results.rows));
deferred.resolve(results.rows);
I would like to be able to get this service to work without having to deep copy every results set that it gets. Can anyone help me understand why this is happening?
I have an app where I need to store artists and their details in database.Now I want to retrieve all the artists and render some of their details in front end.How to do that.
Secondly, if I get the artist rating in some input field by using ng-model, then how to store that value in a particular artist to update details.
The database structure is:
{
"artists": {
"Atif":{
"name":"atif",
"rating":8
},
"Himesh":{
"name":"himesh",
"rating":5
}
}
}
and this is angular.js
(function()
{
var app = angular.module("myapp", ["firebase"]);
app.controller("maincontroller", function($scope, $firebaseObject,$firebaseArray)
{
var ref = new Firebase("https://gigstart.firebaseio.com/");
var artists=ref.child("artists");
// download the data into a local object
$scope.data = $firebaseObject(ref);
// putting a console.log here won't work, see below
ref.on("value", function(snapshot)
{
console.log(snapshot.val());
}, function (errorObject)
{
console.log("The read failed: " + errorObject.code);
});
var artistsRef=new Firebase("https://gigstart.firebaseio.com//artists");
}); //end of controller
Now I want to render the name and rating of each artist in front end.Can I do something like
<div ng-repeat="artist in artists">
{{artist.name}}
{{artist.rating}}
</div>
You have a list of artists, which you want to ng-repeat over in your Angular view. You can accomplish that by:
app.controller("maincontroller", function($scope, $firebaseArray)
{
var ref = new Firebase("https://gigstart.firebaseio.com/");
var artists = ref.child("artists");
$scope.artists = new $firebaseArray(artists);
}
Please take a moment to go through the AngularFire quickstart before starting on your own project. This is covered in step 5.
I am new to Angularjs and am trying to build a news app in phonegap. In this app, a user can select categories such as sports, tech, etc (which are saved in local storage) and only news articles with those categories are displayed to the user. However, when a user selects the categories, they are being saved but I am lost as to how to compare those categories with the category from the news article(the news articles are being pulled from a external website in JSON format which has category along with title and description). Below is the code that I have so far. Any help can be greatly appreciated.
html code:
<div ng-repeat="new in news | limitTo: paginationLimit()">
<img ng-src="{{new.picture}}"alt="{{new.title}}" />
<b class="title">{{new.title}}</b>
<span class="catsource">{{new.category + ' | ' + new.source}}</span>
<p ng-model="letterLimit">{{new.body | limitTo:letterLimit }}...</p>
angularjs code:
app.controller('NewsController', function($scope, $http, NewsData) {
$scope.news = [];
var getData = function ($done) {
$http({method: 'GET', url: NewsData.url}).
success(function(data, status, headers, config) {
if ($done) { $done(); }
$scope.news = data.result;
$scope.letterLimit = NewsData.letterLimit; }); } };
The newsdata.url here is from data.js file which has all the data including url of the external website.
The code below is for categories controller where the categories selected are saved.
app.controller('HomeController', function($scope, Data, localStorageService) {
$scope.items = Data.items;
if (localStorageService.get('items')) {
$scope.items = localStorageService.get('items');
}
$scope.SaveCategories = function () {
localStorageService.clearAll();
localStorageService.add('items',$scope.items);
} )};
I am thinking maybe I can use a filter to filter out the selected categories but it did not work when I tried to do it. Thanks in advance.
if I understand what you want to achieve correctly is that you want to filter the news you receive as json to only include the categories the user has selected?
If so, do something like this:
add this to your NewsController
var filterNews = function(news) {
var k = news && news.length ? news.length : 0;
var i = 0;
var filters = localStorageService.get('items') || null;
var filteredNews = [];
if(!filters) {
return news;
}
//if filters is an array.
for(;i<k;i++) {
if(filters.indexOf(news[i].category) !== -1) {
filteredNews.push(news[i]);
}
}
//If filters is an object.
for(;i<k;i++) {
if(filters[news[i].category]) {
filteredNews.push(news[i]);
}
}
return filteredNews;
};
then call the function when you set this:
$scope.news = data.result;
to
$scope.news = filterNews(data.result);
and also note that you have to import the localStorageService to your NewsController as well
The best case would be if you could specify the categories in the request you make to return only the categories you want
this is what I have in my model
// The contents of individual model .js files will be concatenated into dist/models.js
(function() {
// Protects views where angular is not loaded from errors
if ( typeof angular == 'undefined' ) {
return;
};
var module = angular.module('myModel', ['restangular']);
module.factory('myRestangular', function(Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl('http://localhost/data');
RestangularConfigurer.setRequestSuffix('.json');
RestangularConfigurer.setRestangularFields({
id: "my_id"
});
});
});
})();
this is fine. but now I have another json that I need to grab data from. How could I change this model to look for that other json as well. I am very very new to angular and still learning how model data binding works!
*This is what I have tired *
my model
var module = angular.module('FloorModel', ['restangular']);
module.factory('FloorRestangular', function(Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl('http://localhost/data/floor');
RestangularConfigurer.setRequestSuffix('.json');
RestangularConfigurer.setRestangularFields({
id: "floor_id"
});
});
});
**my controller**
myApp.controller('FloorCtrl', function ($scope, $filter, FloorRestangular) {
// Fetch all objects from the local JSON (see app/models/mdpocket.js)
FloorRestangular.all('floor').getList().then( function(floors) {
// Then select the one based on the view's id query parameter
$scope.floor = $filter('filter')(floors, {floor_id: steroids.view.params['id']})[0];
});
// -- Native navigation
steroids.view.navigationBar.show("Floor: " + steroids.view.params.id );
});
*my view *
<div ng-app="myApp">
<div ng-controller="FloorCtrl">
<div class="topcoat-list__container">
<ul class="topcoat-list">
<li class="topcoat-list__item" hm-tap="open(floor.floor_id)" ng-repeat="floor in floors">
Floor Name: {{ floor.name }}
</li>
</ul>
</div>
</div>
</div>