selected option in ng-options in agularjs - angularjs

I would like to have a selected option in the dynamic select box.
select box not showing any value as selected
$http({
method: 'GET',
url: $rootScope.API_URL + 'branchesShow/' + $routeParams.id,
}).then(function successCallback(response) {
$scope.city_id = response.data.data.city_id;
}, function errorCallback(response) {
// console.log(response);
});
$http({
method: 'GET',
url: $rootScope.API_URL + 'citySelectList',
}).then(function successCallback(response) {
$scope.cities = response.data.data;
console.log($scope.cities);
}, function errorCallback(response) {
console.log(response);
});
<select class = "form-control" ng-model="city_id" ng-options="c.id as c.title for c in cities">
</select>

I think your $scope.city_id doesn't contain an appropriate id value, as i can see you have ng-model directive and an option should be selected if the value in city_id matches an id of an object in your list.
Check if there is something wrong in the data, here is a little snippet to help you :
angular.module('myApp', [])
.controller('MyCtrl', function ($scope) {
$scope.cities = [
{
id: 1,
title: 'City 1'
},
{
id: 2,
title: 'City 2'
},
]
$scope.city_id = 1;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select class = "form-control" ng-model="city_id" ng-options="c.id as c.title for c in cities">
</select>
</div>

Related

Not getting JSON object. AngularJS

I am new in Angular and trying to POST data , but I am getting undefined status. My JSON raw body is like this :
{
"Name": "Something",
"Description": "Something",
"Data": []
}
Name and description is from user input field and Data will be used later to push another JSON object in the array.
I tried but not getting exact output.
Controller:-
app.controller('postController', ['$scope', '$http', 'appService', function ($scope, $http, AppService) {
$scope.addInfos = [{
Name: $scope.name,
Description: $scope.description,
Data: []
}];
$scope.Create = function () {
$scope.addInfos.push({
'Name': $scope.Name,
'description': $scope.Description,
'Data': []
});
$scope.dataObj = {
Name: $scope.name,
Description: $scope.description,
Data: []
};
$http({
method: 'POST',
url: 'http://192.120.27.8:2000/api/Add',
data: $scope.dataObj
}).then(function (data, status, headers, config) {
alert("success");
console.log(data + $scope.Name + $scope.Description);
}, function (data, status, headers, config) {
alert("error");
});
$scope.name = '';
$scope.Description = '';
};
HTML page :-
<div class="input-group col-md-10">
<span class="input-group-addon" id="reg_input" >Name</span>
<input type="text" class="form-control" placeholder="" ng-model="addInfos.name">
</div>
<div class="input-group sepH_b col-md-10">
<span class="input-group-addon" id="reg_input" >Description</span>
<textarea name="reg_textarea" id="reg_textarea" cols="10" rows="3" class="form-control" ng-model="addInfos.description"></textarea>
</div>
<div class="col-md-4">
<a style="" class="btn btn-md btn-primary" ng-click="Create(addInfos)">Create</a>
</div>
The output which I can see in my console is [object Object]. What mistake am I doing here ?
NOTE:- Here I didn't mentioned Data: field as it will be predefined array as of now like this {data:[]} need to inject and pass Name and Description in JSON as I mentioned above.
SECOND also I need to push this over all output data to the Service to store for further use.
Thanks guys , now I can able push necessary datas inside the JSON I did second work around .
$scope.addInfos = {Data: []};
$scope.Create = function() {
$http({
method : 'POST',
url : 'http://192.120.27.8:2000/api/Add',
data : $scope.addInfos
}).success(function(data, status, headers, config) {
growl.success("Created a new File");
console.log(data);
},function (data, status, headers, config) {
growl.error("Something is wrong");
});
};
My second concern is still there , now how to push these data to a service. var something =[];?

Angularjs goes into infinite loop while firing $http function

My app goes into infinite loop while firing $http get method inside a function
In my controller I am using POST and getting data from API after authorization and displaying it.
var app = angular.module('myApp', []);
app.controller('ctrl1', function($scope, $http) {
$http({
url: 'url',
method: "POST",
data: 'postData',
headers: {
'Authorization': 'value'
}
})
.then(function(response) {
$scope.hotels = response.data;
});
$scope.imagePath = function(id) {
console.info(id);
if (id) {
$http({
method: 'GET',
url: 'url=' + id
})
.then(function(response) {
var imgdata = response.data;
console.info(imgdata);
var imgdata1 = imgdata.data.image_name;
return "url" + imgdata1;
});
}
};
});
In my img ng-src I have to call data from another API from the key exterior_image which I am passing in my function but it goes into an infinite loop. Also I know I have to use angular forEach in imgdata1.
<div ng-controller='ctrl1'>
<select ng-options='item as item.hotel_name for item in hotels.data' ng-model='hotel'></select>
<h1>{{hotel.hotel_name}}</h1>
<p>{{hotel.hotel_description}}</p>
<img ng-src="{{imagePath(hotel.exterior_image)}}">
</div>
Try this in your Controller:
var app = angular.module('myApp', []);
app.controller('ctrl1', function ($scope, $http) {
$scope.current_Hotel = {
hotel_name: "Default Value Here",
hotel_description: "Default Value Here",
exterior_image: "Default id here",
image_url: "Default url here"
};
$http({
url: 'url',
method: "POST",
data: 'postData',
headers: {
'Authorization': 'value'
}
}).then(function (response) {
$scope.hotels = response.data;
});
$scope.selectHotel = function () {
$http({
method: 'GET',
url: 'url=' + $scope.current_Hotel.exterior_image
}).then(function (response) {
var imgdata = response.data;
var imgdata1 = imgdata.data.image_name;
$scope.current_Hotel.image_url = "url" + imgdata1;
});
};
});
and this:
<div ng-controller='ctrl1'>
<select ng-options='item as item.hotel_name for item in hotels.data' ng-model='current_Hotel'></select>
<h1>{{current_Hotel.hotel_name}}</h1>
<p>{{current_Hotel.hotel_description}}</p>
<img ng-src="{{current_Hotel.image_url}}">
</div>

How to change variable properties according to drop-down menu item?

I have a drop-down menu populated with ng-options.
<label class="item item-input item-select">
</div>
<div class="input-currencies">
Select Currency
<select ng-options="c.code as c.name for c in currencies" ng-model="codeMod" ng-change="currencyChange(codeMod)">
</select>
</label>
How do I get the value c.code to be the property of the variable named selectedCurrency?
.controller('CurrencyController', function($scope, $http) {
var ngb_currencies = 'http://lari.jumpstart.ge/en/api/v1/nbg_currencies?callback=JSON_CALLBACK'
var selectedCurreny = "" // I want get dropdown code in this variable depending on the selected currency so I make changes in the API
$http.jsonp(ngb_currencies).success(function(currency) {
$scope.currencies = currency.results;
})
.error(function(data) {
alert("ERROR");
});
$http({
method: 'jsonp',
url: 'http://lari.jumpstart.ge/en/api/v1/nbg_rates?callback=JSON_CALLBACK',
params: { currency: selectedCurreny }
}).success(function(data, status , header, config) {
console.log('success');
$scope.result = data.result;
console.log('success');
}).error(function(data, status , header, config) {
console.log('error');
});
First, you have to change c.code as c.name for c in currencies in the ng-options attribute, you can't use a property here, it becomes c as c.name for c in currencies
Then, since you specified ng-model="codeMod", you can watch that variable in your controller, which becomes the following :
.controller('CurrencyController', function($scope, $http) {
var ngb_currencies = 'http://lari.jumpstart.ge/en/api/v1/nbg_currencies?callback=JSON_CALLBACK'
$http.jsonp(ngb_currencies).success(function(currency) {
$scope.currencies = currency.results;
})
.error(function(data) {
alert("ERROR");
});
$scope.$watch('codeMod', function(newSelectedCurreny) {
$http({
method: 'jsonp',
url: 'http://lari.jumpstart.ge/en/api/v1/nbg_rates?callback=JSON_CALLBACK',
params: { currency: newSelectedCurreny}
}).success(function(data, status , header, config) {
console.log('success');
$scope.result = data.result;
console.log('success');
}).error(function(data, status , header, config) {
console.log('error');
});
}
}

How to call ajax on onchange dropdown by angularjs?

My question is
By deafult I am getting result for 1st hotel, how to get results on onchange of hotels dropdown by using angularjs directives ?
My Code
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app='myApp' ng-controller='HttpController'>
{{detail.name}} <br/>
{{detail.address}} <br/>
{{detail.country}}<br/>
</div>
<script>
var hotelid=$('select#hotel_property option:selected').val();
var data = {};
data.Hotelid = hotelid;
data.Action = "hotel_property";
var helloApp = angular.module("myApp", []);
helloApp.controller("HttpController", function($scope, $http) {
$http({
method: 'POST',
datatype:"json",
header: {
"contentType": 'application/json'
},
data: JSON.stringify(data),
url: '/ajax',
}).success(function(data, status, headers, config) {
$scope.detail = data.hotel_details;
}).error(function(data, status, headers, config) {
alert( "failure");
});
});
</script>
<select id="hotel_property">
<option value="111">Taj hotel</option>
<option value="222">oberoi</option>
<option value="333">JW marriot</option>
<option value="444">Grand Maratha</option>
</select>
By deafult I am getting result for 1st hotel, how to get results on onchange of hotels dropdown by using angularjs directives ?
You'll have to do something on these lines.
Use ng-options to populate hotel list
Use ng-model to bind the selected value to some variable
Use ng-change to trigger a function to handle the change.
<select id="hotel_property" ng-model="selectedHotel"
ng-change="fetchInfo(selectedHotel)"
ng-options="hotel.name for hotel in hotels">
<option value="">-- please select -- </option>
</select>
and your controller might look like this.
Defile $scope.hotels with array of hotel id and name.
define a function to fetch hotel information.
helloApp.controller("HttpController", function($scope, $http) {
$scope.hotels = [{
id: 111,
name:'Taj hotel'
},{
id: 222,
name:'oberoi'
},{
id: 333,
name:'JW marriot'
},{
id: 444,
name:'Grand Maratha'
}];
$scope.fetchHotelInfo(hotel){
var data = {};
data.Hotelid = hotel.id;
data.Action = "hotel_property";
$http({
method: 'POST',
datatype:"json",
header: {
"contentType": 'application/json'
},
data: JSON.stringify(data),
url: '/ajax',
}).success(function(data, status, headers, config) {
$scope.detail = data.hotel_details;
}).error(function(data, status, headers, config) {
alert( "failure");
});
}
});
(Copy pasting code might not work)
Hope this helps!
You can use ng-model directive to store the selected value in the scope and use ng-change to fire the ajax query with the model value as parameter.
https://docs.angularjs.org/api/ng/directive/select

AngularJS - ng-repeat - using parent repeat data in child http request

I have what would seem to be a simple problem with AngularJS - apologies if so. I'm new and have searched all over and can't quite find an answer to what I want to do.
Basically I have a $http request that is getting a list of 'Cards' from a server which I'm then using ng-repeat to build in the HTML. I then want to populate those Cards with a number of 'Metrics' - also retrieved from the server. I have a controller for the 'Cards' (parents) and a separate controller for the 'Metrics' (children).
My issue is that I can't work out how to reference the ID of the parent 'Card' when making the child $http request.
Below is the HTML & JS that I am using - any help would be appriciated:
HTML:
<div class="Dashboard container-fluid" ng-controller="DahsboardCardController as Dashboard">
<div ng-repeat="Card in Dashboard.DashboardCards">
<div class="DashboardCard card">
{{Card.CardDisplayName}}
<div class="DashboardCardBody" ng-controller="DahsboardMetricController as Metric">
<div ng-repeat="Metric in Metric.DashboardMetrics">
{{Metric.MetricDisplayName}}
</div>
</div>
</div>
</div>
JS:
(function () {
var app = angular.module('OtterDashboard', [ ]);
app.controller('DahsboardCardController', [ '$http', function($http) {
//Declare a varaible for the data
var DashboardCards = this;
//Set the varaiable to an empty array to receive the data
DashboardCards.DashboardCards = [ ];
$http({
//Request the data
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/tbl_Card',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
//The data was sucessfully received, populate the variable with it
DashboardCards.DashboardCards = data.data.d.results;
}, function errorCallback(response) {
//There was an error
console.log('Card data could not be retrieved');
});
}]);
app.controller('DahsboardMetricController', ['$http', function($http, Card) {
//Declare a varaible for the data
var DashboardMetrics = this;
//Set the varaiable to an empty array to receive the data
DashboardMetrics.DashboardMetrics = [ ];
$http({
//Request the data
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/DashboardMetric?Card=%27' + **???reference to parent card ID???** + '%27',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
//The data was sucessfully received, populate the variable with it
DashboardMetrics.DashboardMetrics = data.data.d.results;
}, function errorCallback(response) {
//There was an error
console.log('Metric data could not be retrieved');
});
}]);
})();
Thank you!
EDIT 1
Use a service for shared variable between controllers. Look the example:
app.controller('DahsboardCardController', ['$http', function($http, $sharedResource) {
var DashboardCards = this;
DashboardCards.DashboardCards = [ ];
$http({
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/tbl_Card',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
DashboardCards.DashboardCards = data.data.d.results;
$sharedResource.set("id", "<pass id value>");
}, function errorCallback(response) {
console.log('Card data could not be retrieved');
});
}]);
app.controller('DahsboardMetricController', ['$http', function($http, Card, $sharedResource) {
var DashboardMetrics = this;
DashboardMetrics.DashboardMetrics = [];
$http({
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/DashboardMetric?Card=%27' + $sharedResource.get("id") + '%27',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
DashboardMetrics.DashboardMetrics = data.data.d.results;
}, function errorCallback(response) {
console.log('Metric data could not be retrieved');
});
}]);
app.factory('$sharedResource', function () {
var property = {};
return {
get: function (key) {
return property[key];
},
set: function(key, value) {
property[key] = value;
}
};
});
EDIT 2
When working with angularjs is recomended use a one object for print object in table. Why this is a beautiful s2.
Look this example. To help you in development. Use the sample function pass the parentId in load(CardId). This function will run in the page load.
I too fix code html. You used the alias controller before input field of same.
var app = angular.module("App", []);
app.controller('DahsboardCardController', ['$scope', function($scope) {
$scope.DashboardCards = [{
CardId: "111",
CardDisplayName: "Card 1"
}, {
CardId: "222",
CardDisplayName: "Card 2"
}, {
CardId: "333",
CardDisplayName: "Card 3"
}];
}
]);
app.controller('DahsboardMetricController', ['$scope', function($scope) {
$scope.load = function(CardIdParent) {
console.log(CardIdParent);
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" class="Dashboard container-fluid" ng-controller="DahsboardCardController as Dashboard">
{{Dashboard.DashboardCards}}
<div ng-repeat="Card in DashboardCards">
<div class="DashboardCard card">
{{Card.CardDisplayName}}
<div class="DashboardCardBody" ng-controller="DahsboardMetricController as Metric" ng-init="load(Card.CardId)">
This a id parent: {{Card.CardId}}
<div ng-repeat="MetricItem in DashboardMetrics">
{{MetricItem.MetricDisplayName}}
</div>
</div>
</div>
</div>
</div>

Resources