Filling a select not firing angular controller - angularjs

I am trying to fill an HTML select using angular. I tested the API and got something like:
{"Countries":[{"Id":1,"Name":"Andorra"},{"Id":2,"Name":"France"}]}
The HTML is the following:
<form id="form" method="post" ng-submit="submit">
<select ng-model="model.currentCountry" ng-options="country.Id as country.Name for country in model.countries" ng-controller="CountryController">
<option value="">Country</option>
</select>
</form>
Then I have the JS code:
var application = angular.module('Application', []);
application.service('CountryService', function ($http) {
return {
GetList: function () {
return $http.get('api/countries');
}
}
});
application.controller('CountryController', function CountryController($scope, CountryService) {
alert("Country Controller");
$scope.model = {
currentCountry: '',
countries: []
}
CountryService.GetList()
.success(function (data, status, headers, config) {
$scope.model.countries = $scope.model.countries.concat(data)
})
.error(function (data, status, headers, config) { });
});
Somehow not even the alert in CountryController gets fired.
Any idea what am I missing?

In the success handler in your controller you have....
$scope.model.countries = $scope.model.countries.concat(data)
So you are concatting the Countries object from your example JSON, change that to this:
$scope.model.countries = $scope.model.countries.concat(data.Countries)
This way you are concatenating the actual array of countries to your model.countries.
Edit here is an example plnkr to play with

Related

Angular 1:Build dropdown box dynamically

I am new to Angular 1,so I am stuck with building a dropdown box dynamically using angular.
Below is my code
var app = angular.module('myApp', []);
app.controller('TestCtrl', function($scope, $http) {
I have created an onchange function getTypeName() and have passed the parameters using get method and retrieved the result as json .
$scope.getTypeName = function (type) {
$http.get('get-type-name',
{ params:
{
type: type
}
}).then(
function(response){
var data = response.data;
for(i = 0; i < data.length; i++) {
//code to build dropdown
}
},
);
}
});
Below is my response,
[
{"id":"001","name":"ABC"},
{"id":"002","name":"DEF"},
{"id":"003","name":"GHI"}
]
I want to build a dropdown box using this response within the get method function success using for loop.Please provide a solution to solve this out.
you do like this
in app.js
$scope.getTypeName = function (type) {
$http.get('get-type-name',
{ params:
{
type: type
}
}).then(
function(response){
$scope.data = response.data;
},
);
}
});
in your html
<select id="ddl" model="ddldata" typeof="text"required>
<option data-ng-repeat="ProjectName in data" value="{{ProjectName.id}}" ng-bind={{ProjectName.name}}">
</select>
You can try this,
$scope.yourOptions = [];
$scope.getTypeName = function (type) {$http.get('get-type-name',
{ params:
{
type: type
}
}).then(
function(response){
var data = response.data;
$scope.yourOptions = data;
},
);
}
});
in html,
<select class="form-control" ng-model="whatever" >
<option ng-repeat="x in yourOptions " value="{{x.id}}">{{x.name}}</option>
</select>
Here is an example of dynamically populating select options from an http get https://plnkr.co/edit/7PS7LBBNZA2cNzMorrB9?p=preview
<select ng-model="selectedItem">
<option ng-repeat="o in options">{{o.name}}</option>
</select>
$scope.getTypeName = function() {
$http.get('https://jsonplaceholder.typicode.com/users').then(
function(result) {
$scope.options = result.data;
},
function(error) {
console.log(error);
}
);
};

Unable to set selected value in AngularJS

i have several select boxes on my edit form, now when the page loads data is loaded into it, this works for all textboxes and checkboxes but not selectboxes, i am unable to set the selected value for them i have googled so many things but i still cannot seem to find what i am doing wrong, this is my html:
<div class="form-group" ng-init="getRoles()">
<label for="roles">Role</label>
<select style="width: 100%;" data-toggle="select2" ng-model="form.role_id" ng-options="item.id as item.role for item in roles">
</select>
</div>
This is the function that gets and sets the user info in my controller:
$scope.getUserInfo = function() {
UserService.get($stateParams.id)
.success(function (data, status, headers, config) {
if (data.user != undefined)
{
$scope.form = data.user;
}
})
};
This the function that gets and sets the roles in my controller:
$scope.getRoles = function() {
RoleService.get()
.success(function (data, status, headers, config) {
if (data.roles != undefined)
{
$scope.roles = data.roles;
}
})
};
I have verified the returned data and it is indeed correct.
This is the returned JSON:
{"user":{"id":2,"email":"xxxxxxx#gmail.com","role_id":2,"institution_id":null,"is_active":1}}
And this is the returned roles JSON:
{"roles":[{"id":2,"role":"System"},{"id":3,"role":"Administrator"},{"id":4,"role":"Instructor"}]}
You need to write
ng-model="user.role_id"

Update model outside of controller

Just starting out on angular, not sure how to update a model out of a controller, or in fact if have my head around exactly what to do. I have an autocomplete field based on ion.autocomplete
HTML
<span ng-controller="IonAutocompleteController">
<label class="item item-input item-stacked-label">
<span class="input-label">Item Description</span>
<ion-autocomplete ng-model="model"
item-value-key="name"
item-view-value-key="view"
items-method="getTestItems(query)"
multiple-select="false"
placeholder="Bread, Milk, Eggs etc .."
items-clicked-method="itemsClicked(callback)"/>
</span>
<button class="button button-block button-royal" ng-click="scan()">Scan</button>
<div class="row">
<div class="col"><b>Item Name</b></div>
<div class="col" ng-model="name"></div>
</div>
Javascript
var myApp = angular.module('myApp', ['ionic','ngCordova','ion-autocomplete']);
myApp.config(['$ionicConfigProvider', function($ionicConfigProvider) {
$ionicConfigProvider.tabs.position('bottom')
}]);
myApp.controller('IonAutocompleteController', function ($scope,$http) {
$scope.model = "";
$scope.callbackValueModel = "";
$scope.getTestItems = function (query) {
console.log(query);
return $http.get('http://192.168.100.100/myApp/products/' + query).
success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
console.log("something went wrong")
});
};
$scope.itemsClicked = function (callback) {
console.log(callback);
$scope.name=callback.item.name;
console.log(callback);
$scope.callbackValueModel = callback;
}
});
What is happening here is the autoselect is grabbing data from a REST server and the results are place in the autocomplete. When the item is selected callback is returned in a json array. I want the callback to be place in ng-model="name" but it is out of the controller. Or I assume that is why it is not updating.
your ng-Model="name" binds to $scope.name in your controller. When data is returned from the REST call, just set $scope.name = data.
Two problems here.
1/ there is a missing </label>.
2/ should be using ng-bind NOT ng-model which is for inputs
You need to populate your view with autocomplete data based on what the success callback returns, not return the $http as an invocation.
$http.get('http://192.168.100.100/myApp/products/' + query).
success(function(data, status, headers, config) {
console.log(data);
// Do whatever you need to do to data before binding it,
//such as extracting a value from the JSON, etc.
$scope.model = data;
}).error(function(data, status, headers, config) {
console.log("something went wrong")
});
};

MEAN with Jade template form submit GET instead of POST

So, earlier today I had a working form that could post and delete restaurants documents to a mongodb collection. Everything was working fine, but then I decided to try and load the form into a div instead of redirect to a new page. Doing so produced a different result when I tried to submit my restaurant form. Originally it would call $scope.add() in my restaurantsController, but now it is sending a GET request with form data to /restaurants instead of a POST to /api/restaurants. I'm looking for some insight as to what I did to change the behavior. Although it is loading the form when I click on my restaurant anchor tag, it is not loading the restaurants from the database.
Here is the jade and js for the menu anchors:
menu.js
app.controller("menu", ["$scope", "$http", function ($scope, $http) {
$scope.home = function () {
$("#content").html("");
};
$scope.restaurants = function () {
$http.get('/restaurants').
success(function(data, status, headers, config){
$("#main_content").html(data);
}).
error(function(data, status, headers, config){
});
};
}]);
nav.jade
mixin link(name, fn)
li
a.btn(ng-click=fn)= name
nav.navbar.navbar-inverse.navbar-fixed-top(role='navigation')
.container
.navbar-header
button.navbar-toggle.collapsed(type='button', data- toggle='collapse', data-target='#navbar', aria-expanded='false', aria- controls='navbar')
span.sr-only Toggle navigation
span.icon-bar
span.icon-bar
span.icon-bar
a.navbar-brand(href='/') Food App
#navbar.navbar-collapse.collapse
ul.nav.navbar-nav(ng-controller="menu")
+link("Home", "home()")
+link("Restaurants", "restaurants()")
And here is the form:
form(name="NewRestaurant" ng-submit="$event.preventDefault();add()")
.row
.form-group
input.form-control(type="text", name="name" placeholder="Name", ng-model="name" required)
.row
.form-group
input.form-control(type="text", name="address" placeholder="Address", ng-model="address" required)
.row
.form-group.col-md-6
-for(var i = 0; i <= 5; i++){
input(name="rating" type="radio", value=i, ng-model="rating" required)
=i
-}
.form-group.col-md-6
button.success(type="submit") Submit
and the controller...
app.controller("restaurants", ["$scope", "$resource", function ($scope, $resource) {
var Restaurant = $resource('/api/restaurants/:id');
var clearForm = function () {
$scope.name = '';
$scope.address = '';
$scope.rating = null;
}
clearForm();
var validRestaurant = function () {
if($scope.name !== '' && $scope.address !== '' && $scope.rating !== null)
return true;
else{
toastr.error("Please fill in all required form fields.");
return false;
}
}
$scope.query = function(){
Restaurant.query(function (results) {
$scope.restaurants = results;
});
};
$scope.add = function () {
alert("got here!");
if(validRestaurant()){
var restaurant = new Restaurant();
restaurant.name = $scope.name;
restaurant.address = $scope.address;
restaurant.rating = $scope.rating;
alert(restaurant);
Restaurant.save(restaurant, function (result) {
$scope.restaurants.push(result);
toastr.success("Saved " + $scope.name + ".")
clearForm();
});
}
};
$scope.update = function (id) {
};
$scope.remove = function (id) {
console.log(id);
Restaurant.delete({id: id}, function (err) {
console.log(err);
$scope.query();
});
};
$scope.query();
}]);
edit: Now that I am typing this up, I am wondering, maybe angular doesn't recognize the form and doesn't create a $scope for it because it gets loaded after the page loads...?

How to Dismiss Angular Modal

I am using Ekathuwa modals, I need to close it after a successfull Ajax PUT. I am trying to follow the examples they give. I am able to close the modal, but there is still a grey color on the screen. Like it is still open in the background? I still need to refresh the page for it to go away.
$scope.updateJob = function (job) {
console.log($scope.currentItem);
job.JobTypeId = $scope.currentItem.JobType.JobTypeId;
job.JobClassId = $scope.currentItem.JobClass.JobClassId;
job.GeoAreaId = $scope.currentItem.GeoArea.GeoAreaId;
jobFactory.updateJob(job).success(successCallback)
.error(errorCallback);
console.log(job);
var p = $ekathuwa.modal({
id: "EditJobModal", contentStyle: "width:800px;heigth:400px",
scope: $scope,
templateURL: "views/modals/EditJobModal.html"
});
$q.when(p).then(function (m) {
m.modal('hide');
});
};
var successCallback = function (data, status, headers, config) {
notificationFactory.success();
};
var errorCallback = function (job, status, headers, config) {
notificationFactory.error(job.ExceptionMessage);
};
Move hide modal logic to successCallback function.
I don't know your editable fields on "views/modals/EditJobModal.html" or other pages.
If it is on EditJobModal.html, Better to used two functions, one for create and open modal other for your update logic.
thanks,
Sarath
Update
//Edit Job Modal
$scope.EditJobModal = function (id) {
$.get('/api/apiJob/' + id, function (data) {
console.log(data);
$scope.currentItem = data;
$scope.openEditJobModal = $ekathuwa.modal({
id: "EditJobModal", contentStyle: "width:800px;heigth:400px",
scope: $scope,
templateURL: "views/modals/EditJobModal.html"
});
//show modal window
$scope.openEditJobModal.then(function (m) {
m.modal('show');
});
});
}
//Update Job
$scope.updateJob = function (job) {
console.log($scope.currentItem);
job.JobTypeId = $scope.currentItem.JobType.JobTypeId;
job.JobClassId = $scope.currentItem.JobClass.JobClassId;
job.GeoAreaId = $scope.currentItem.GeoArea.GeoAreaId;
jobFactory.updateJob(job).success(successCallback)
.error(errorCallback);
console.log(job);
};
var successCallback = function (data, status, headers, config) {
//hide modal window
$scope.openEditJobModal.then(function (m) {
m.modal('hide');
});
notificationFactory.success();
};
var errorCallback = function (job, status, headers, config) {
notificationFactory.error(job.ExceptionMessage);
};
Modal
<input type="submit" ng-click="updateJob(currentItem)" value="Submit" />
<input type="button" ng-if="true" data-dismiss="modal" value="Exit" />
Seems to be a bug in AngularUI. See this: https://github.com/angular-ui/bootstrap/issues/1643
The modal scope is not being destroyed correctly on either close or dismiss.

Resources