Show images from array in Angularjs - angularjs

Images path are stored in database and I am fetching them from http request.
Data is in array format.
Sample data:
{"success":true,"img":["portfolio_img\/40306762187.jpg","portfolio_img\36272080187078.jpg","portfolio_img\/36211374209814.jpg","portfolio_img\/36272058183542.jpg"]}
I am want to show those images in html page.
Here is the http request code.
var formApp = angular.module('formApp', []);
formApp.controller('getprofile', function($scope,$http){
$http({
url: 'get_pics.php',
method: "GET",
params: {uid: uid}
})
.success(function(data) {
if (data.success) {
//forEach($scope.data,function(value,index){
// alert(value.img);
//})
}
});
})
HTML code is here.
<div ng-controller ="getprofile">
<div class="row"><div id="grid">
<fieldset ng-repeat="choice in choices"> (Need to modify)
<div class="col-xs-3 thumbnail">
<img src="" ng-src="{{imageUrl}}" ng-model="choice.course">(Need to modify)
</div>
</fieldset>
</div></div>
</div>
I am still working on code. So, there should be some error and typos.

Try this,
var formApp = angular.module('formApp', []);
formApp.controller('getprofile', function($scope,$http){
$http({
url: 'get_pics.php',
method: "GET",
params: {uid: uid}
})
.success(function(data) {
if (data.success) {
angular.forEach(data,function(value,index){ // Angular foreach
$scope.images = data.img; // data in images scope variable.
})
}
});
})
In HTML
<div ng-controller ="getprofile">
<div class="row"><div id="grid">
<!-- loop images scope variable -->
<fieldset>
<div class="col-xs-3 thumbnail" ng-repeat="imageUrl in images">
<img src="" ng-src="{{imageUrl}}" ng-model="choice.course">
</div>
</fieldset>
</div></div>
</div>

Related

$http.get(...).success is not a function

So I'm working on a small app with angular 1 with file uploading and I found out that there were changes that I wasn't aware of as the way coding https in a controller is different now. As the old way now causes http.get.success is not a function. I need help understanding what changes from 1.4 angular 1 to the current version that I have to do now with my controllers so my data from my rest API show up on my HTML. As I'm getting $http.get(..).success is not a function error now.
gallerycontroller
var galleryCtrl = angular.module('galleryCtrl', []);
galleryCtrl.controller('galleryController', function($scope, $http) {
$scope.superheroes= [];
//Retrieve all the superheroes to show the gallery
$http({
method: 'GET',
url: '/superhero'
})
.success(function (data, status, headers, config) {
console.log(data);
})
.error(function (data, status, headers, config) {
console.log(data)
})
});
gallery.html
<!-- view the gallery of all the superheroes in the db -->
<div class="row">
<div ng-repeat="superhero in superheroes">
<div class="col-md-4 col-xs-6 col-sm-offset-0">
<div class="thumbnail">
<img ng-src="{{superhero.picture.url | fpConvert: {filter:'sharpen', w:300, h:150} }}" />
<div class="caption text-center">
<h3>{{superhero.name}}</h3>
<p><label>Super powers: </label> {{superhero.superPowers}}</p>
<div class="text-right"><a ng-href="/#/detail/{{superhero._id}}" class="btn btn-danger" role="button">View</a> </div>
</div>
</div>
</div>
</div>
</div>
Success is deprecated. Use then.
$http.get().then(function success(result){
}, function error(err) {
})

How to dynamically call data from an API when option is selected

Suppose there are two hotels in my options in select tags and I want my h1 to change when I select one of the options. How do I achieve this
I am using POST method to authorize and call data in my reservationCtrl and display the hotel_name in my select tags.
<div class="container">
<div class = "row" ng-controller="reservationCtrl">
<div class="form-group">
<label for="sel1">Select a Hotel:</label>
<select class="form-control" id="sel1">
<option ng-repeat="x in hotels.data">{{x.hotel_name}}</option>
</select>
</div>
</div>
And I am using GET method to call data from another API to display the hotel_name.
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1 ng-repeat="x in hotel.data">{{x.hotel_name}}</h1>
</div>
</div>
</div>
Here is my showController and I want my hotel id to change like from 72 to 35 when I click one of the options so that it will call data from a different API and display a different name in the headers.
(function(){
angular
.module("reservationModule")
.controller("showCtrl", function($http, $scope, $log){
$http({
method: 'GET',
url: '&hotel_id=72'})
.then(function (response) {
$scope.hotel = response.data;
}, function (reason){
$scope.error = reason.data;
$log.info(reason);
});
});
})();
Here is the reservationController
(function(){
angular
.module("reservationModule")
.controller("reservationCtrl", function($http, $scope, $log){
$http({
url: '',
method: "POST",
data: 'postData',
headers:{ 'Authorization': 'value'}
})
.then(function(response) {
$scope.hotels = response.data;
}
);
});
})();
Yes you can add ng-change and achieve your functionality as below
JS code
var app = angular.module('myApp', []);
app.controller('ctrl1', function($scope) {
$scope.hotels = [{
name: 'Taj',
id: 1
}, {
name: 'Royal',
id: 2
}];
$scope.hotelInfo = {};
$scope.fetchData = function() {
// here call service which will fetch data and assign to hotel data
$scope.hotelInfo = {
address: 'London'
};
}
});
app.controller('ctrl2', function($scope) {
$scope.data = ''
});
HTML code
<div ng-app='myApp'>
<div ng-controller='ctrl1'>
<select ng-options='item as item.name for item in hotels' ng-model='hotel' ng-change='fetchData()'>
</select>
{{hotel}} - {{hotelInfo}}
</div>
</div>
Here is the link Jsfiddle demo
You need to call event on the select box which will call simple function which return the data like following
<select ng-options="size as size.name for size in sizes"
ng-model="item" ng-change="update()"></select>
write javascript code on the update function
Your can use ng-change on select of particular hotel.
In congroller :
$scope.showHotel = function(hotelName){
$scope.selectedHotel = hotelName;
}
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1 ng-repeat="x in hotel.data" ng-change="showHotel(x.hotel_name)">{{x.hotel_name}}</h1>
</div>
</div>
In view you you can edit like this if you have to display only one hotel name instead of ng-repeat:
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1>{{selectedHotel}}</h1>
</div>
</div>

How do I open a modal from a controller using Angular-materialize

I am using Materialize CSS and the Angular-materialize directives:
http://materializecss.com/modals.html
http://krescruz.github.io/angular-materialize/#modals
I am trying to do the following
User clicks button
Controller action gets fired and we go get data from an api
Modal is displayed to user and data returned is displayed
I have the following button
<a href="#MyModal" modal class="my-modal-trigger waves-effect waves-green btn right"Show Data/a>
and modal
<div id="MyModal" class="modal">
<div class="modal-content center">
<div class="row">
<div class="row left">
<div class="card blue-grey darken-1">
<div class="card-content white-text">
<span class="card-title">Data</span>
</div>
<div>
<ul class="collection">
//loop the data
</ul>
</div>
</div>
<a class="modal-action modal-close waves-effect waves-green btn">Close</a>
</div>
</div>
</div>
</div>
and i have the following in my JS
var app = angular.module("MyApp", ['ngRoute', 'ui.materialize']);
How can i call a controller method to pop up the modal and fill it with data, from my controller
app.controller('mainController', function ($scope, $location, $http, AppConfig) {
var params = { some stuff}
$http({
method: 'POST',
url: myURL,
headers: {
'Content-Type': 'text/html',
'Accept': 'application/json'
},
params: params
})
.success(function (data) {
//pop up the modal and show the data
Materialize.toast('Awesome, we got the data', 4000);
})
.error(function (status) {
Materialize.toast('Bad stuff happened', 4000);
});
});
Angular-materialize lets you set an option open in your trigger. Use it to specify a variable that, when true, will launch your modal. Set it to false initially in your controller.
Use ng-click to call a function in your controller that fetches data from your API then sets the open variable to true on success.
Trigger:
<a href="#MyModal" class="btn" modal open="openModal"
ng-click="getDataOpenModal()">Show Data</a>
In Controller:
$scope.openModal = false;
$scope.getDataOpenModal = function() {
$http({
method: 'POST',
url: '/myUrl',
headers: {
'Content-Type': 'text/html',
'Accept': 'application/json'
},
params: params
})
.success(function(data) {
$scope.data = data;
$scope.openModal = true;
Materialize.toast('Awesome, we got the data', 4000);
})
.error(function(status) {
Materialize.toast('Bad stuff happened', 4000);
});
}
EDIT: There are two other options you can set in your trigger, ready and complete
HTML
<a href="#MyModal" class="btn" modal open="openModal"
ready="readyCallback()" complete="completeCallback()"
ng-click="getDataOpenModal()">Show Data</a>
JS
$scope.readyCallback = function() {
Materialize.toast("Modal ready", 4000);
}
$scope.completeCallback = function() {
Materialize.toast("Modal complete", 4000);
}
Worked for me with $scope.$apply() after $scope.openModal = true;
I was fighting with this too, but no solution worked for me. I had to change html side.
My html:
<i class="zmdi zmdi-eye"></i>
In controller:
$scope.openModal = false
$scope.get_info_log = function(){
$scope.openModal = true;
}
Data-target should match your modal id:
!-- Modal Structure-->
<div id="log_detail" class="modal modal-fixed-footer setup-modal">
<div class="modal-content">
</div>
</div>
<div class="modal-footer">
<a class=" modal-action modal-close waves-effect waves-light btn">Close</a>
</div>
</div>

AngularJS Codeigniter base_url path settings

I am creating a website with Codeigniter 3 and AngularJs. While delevolping i have faced some issues with base url in codeigniter. Im attaching an image file of my directory struture.
In my mainpage(views/home.php) i put a ng-view for loading different pages. Here i am using angularjs ngRoute for routing.
Here is my code.
var myApp = angular.module("myApp",["ui.bootstrap","ui.router","ngRoute"]);
myApp.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "application/pages/mainpage.php"
})
.when("/about", {
templateUrl : "application/pages/about.html"
})
.when("/services", {
templateUrl : "application/pages/services.html"
})
.otherwise("/",{
templateUrl: "application/pages/mainpage.php"
});
});
Inside that mainpage.php i am listing some profile contents(dummy contents) which is residing inside a json file(datas/data.json). And all the content were listing. And inside this listing i placed a button with ng-click="myName"
Here is the code:
<div class="container" ng-controller="ListController">
<div class="row">
<div class="col-lg-12 text-center">
<h1>Starter Template</h1>
<p class="lead">Complete with pre-defined file paths that you won't have to change</p>
<div class="row">
<div class="col-sm-6 col-md-4 wow zoomIn" data-wow-delay="0.5s" ng-repeat="items in artists">
<div class="thumbnail">
<img ng-src="{{settings.base_url}}/application/assets/images/profile/{{items.shortname}}.jpg" alt="...">
<div class="caption">
<h3>{{items.name}}</h3>
<p>{{items.bio}}</p>
<p>Button Button</p>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.row -->
</div>
All my js code were wriiten in app.js(assets/js/app.js) including Angular Js. In this js file i have setup a base_url variable same as in codeigniter config.php file
$config['base_url'] = 'http://localhost/AngularExPack/Angular_Bootstrap_CI_1/';
inside app.js
var base_url= 'http://localhost/AngularExPack/Angular_Bootstrap_CI_1/'
When i click on my button with ng-click="myName" i want to get a controller(Codeigniter controller) and want to execute a function inside that controller. Here iam using auth.php(controllers/auth.php) and function name as functionOne();
public function functionOne()
{
/*$this->load->view('home1');*/
echo "hai";
}
For that iam using $hhtp.post and var base_url for path. But i didnt get that output and it is not passing to that controller.
myApp.controller('ListController', ['$scope', '$http', 'settings', function($scope, $http) {
$http.get('application/datas/data.json').success(function(data) {
$scope.artists = data;
});
$scope.myName = function() {
alert("hai1");
/**/
$http.post(base_url + 'auth/functionOne').success(function(response) {
$scope.data = response
console.log($scope.data);
alert($scope.data);
});
}
}]);
ng-click="myName" function works fine. But it is not passing to the function functionOne inside that controller auth.php. I think the issue is probably with the base_url path. If any one knows this plz help me to solve this issue.
Well, I don't know it this will help you, but this is how I am doing it:
I have this function in a service:
saveFunction: function(obj, user, securityToken){
return $http({
method: 'POST',
url: 'index.php/controller/saveFUnction',
data: $.param({
postID: obj.id ,
csrfTokenName: securityToken,
postName: obj.name,
.....
userID: user.id
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
if your csrfToken is active in codeigniter config, you need to pass it in your form, as hidden type field. Also, you must set the content type in the headers.

AngularJS access $http return json array

i have older post which i deleted i solved it there.
I have other issue:
I have this data array came from PHP with $http(i use console.log):
I can't access that data with ng-repeat:
ibids.controller("auctions",function($http){
var req = {
method: 'POST',
url: 'includes/bids.php',
headers: {
'Content-Type': 'json'
},
data: 'q=getAuctions'
}
$http(req).then(function(req){
console.log(req);
var auctionslist = req.data;
}, function(){
});
});
html:
<body ng-controller="auctions as auction">
<input type="text" value="test" ng-model="man">
{{man}}
<hr>
<div class="search" >
<input type="text">
<div class="res" ng-repeat="x in auction.auctionslist">
{{x}}
</div>
</div>
</body>
What is wrong here ? i recive json data from php and perfect assign to data array in $http .when i use console.log(req) this is what you see in the pictures and its recive the json array perfect.
i don't know how to use ng-repeat on that data .
You have to use $scope and add a property on it for this data and use it in template
ibids.controller("auctions",function($http, $scope){
var req = {
method: 'POST',
url: 'includes/bids.php',
headers: {
'Content-Type': 'json'
},
data: 'q=getAuctions'
}
$http(req).then(function(req){
console.log(req);
$scope.auctions = req.data;
}, function(){
});
});
and in html
<body ng-controller="auctions">
<input type="text" value="test" ng-model="man">
{{man}}
<hr>
<div class="search" >
<input type="text">
<div class="res" ng-repeat="auction in auctions">
{{auction}}
</div>
</div>

Resources