First time asking a q, so if I'm doing something wrong, please let me know so I can fix it as I have tried finding the answer on here, but can not, so any and all help would be greatly appreciated.
I'm trying to load a list of "Countries" using a controller and all seems to be going well, no errors, no warnings, it loads the module and hits the angular controller, but it never hits the function/goes into the code inside the function of the controller. Am I missing something? Am I doing something wrong?
Register.cshtml
<div ng-app="RegisterApp" class="form-group" ng-controller="CountriesController as CountriesCtrl">
<label class="input-desc">Country</label>
<select ng-model="country"
ng-options="country.Id as country.Name for country in countries">
<option value="{{CountriesCtrl.country.Id}}">{{CountriesCtrl.country.Name}}</option>
</select>
</div><!-- End .from-group -->
RegisterApp.js
var app = angular.module("RegisterApp", []);
CountriesService.js
/// <reference path="../App.js" />
angular.module("RegisterApp").service("CountriesService", function ($http) {
this.getCountries = function () {
return $http({
method: "Get",
url: "/Account/GetCountries"
});
};
});
CountriesController.js
/// <reference path="../Services/CountriesService.js" />
angular.module("RegisterApp").controller("CountriesController", function ($scope, CountriesService) {
getCountries();
function getCountries() {
CountriesService.getCountries()
.success(function (data, status, headers, config) {
$scope.countries = data;
$scope.country = $scope.countries[0];
})
.error(function (data, status, headers, config) {
$scope.message = 'Unexpected Error';
});
}
});
Edit: Moved the ng-app, was mistakenly copied over like that, was a change I made just to try something before posting the q, sorry for that
ng-app must be registered before ng-controller (Or on same element). You have registered it in a child-element (select) to the element with ng-controller
Change your HTML to:
<div ng-app="RegisterApp" class="form-group" ng-controller="CountriesController as CountriesCtrl">
<label class="input-desc">Country</label>
<select ng-model="country"
ng-options="country.Id as country.Name for country in countries">
<option value="{{CountriesCtrl.country.Id}}">{{CountriesCtrl.country.Name}}</option>
</select>
</div>
Have a look at this JSFiddle.
Your code must be:
<div ng-app="RegisterApp">
<!-- some beautiful html -->
<div class="form-group" ng-controller="CountriesController as CountriesCtrl">
<label class="input-desc">Country</label>
<select ng-model="country" ng-options="country.Id as country.Name for country in countries">
<option value="{{CountriesCtrl.country.Id}}">{{CountriesCtrl.country.Name}}</option>
</select>
</div>
<!-- some beautiful html -->
</div>
Notice ngApp directive usage.
Also, check that all of your dependencies are injected correctly (I mean <head> block)
Related
I am trying to implement a multiselect dropdown in AngularJS and trying to store the values in an list in my JS file. However I am unable to handle the event for selecting multiple values.
I have used ng-change but this handles only one click. Selecting multiple values using CTRL + arrow key is not handled. My list is dynamically generated.
Please suggest ways to handle it using Javascript/AngularJS
<div>
<select multiple class="form-control drop-down" name="abclist" id="users" ng-model="databaseUser" ng-options="databaseUser.username for databaseUser in databaseUsers" ng-change="ctrl.onchange()" required>
<option value="" >SELECT USER VALUE</option>
</select>
</div>
(function () {
'use strict';
angular.module(userdetails.module).controller('UserController', UserController);
UserController.$inject = ['$scope', '$rootScope','$http', 'dData', '$location', '$uibModal'];
function AdminController($scope, $rootScope, $http, dData, $location, $uibModal) {
function onchange(){
}
You don't need to catch the onChange event to do that, the ng-model attribute will do the work for you.
HTML
<div ng-app="myModule">
<div ng-controller="myController as ctrl">
<div>
<p>Selected users: {{ctrl.selectedUsers}}</p>
<select multiple
id="users"
ng-model="ctrl.selectedUsers"
ng-options="user as user.label for user in ctrl.users track by user.id">
</select>
</div>
</div>
</div>
Javascript
var module = angular.module("myModule", []);
module.controller("myController", function() {
var $ctrl = this;
$ctrl.users = [{id:1, label:'eyp'}, {id:2, label:'jrt'}];
$ctrl.selectedUsers = null;
});
Here you have a JSFiddle test to show you how it works.
I'm a newbie to Webapi with AngularJS. I have a URL which will give data in JSON format, I need to catch only employeename from the given data and pit it in drop down list in AngularJS. Any help appreciated.
you can use $filter to filter out data from the Json array like below,
$filter('filter')(your json array, { column name: value}, true)
Hope this will help.
You can try this <select name="{{option.empname}}" ng-model="modelName" ng-options="option for option in empdetail">
</select>
For more detail, refer here
Please take a look at this simple full qualified demo fiddle.
View:
<div ng-controller="MyCtrl">
<select ng-model="selected"
ng-options="option.name for option in options"></select>
</div>
AngularJS application:
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope, $http) {
$scope.options = [];
$scope.selected = null;
$http({
method: 'GET',
url: 'https://jsonplaceholder.typicode.com/users'
}).then(function (result) {
$scope.options = result.data;
$scope.selected = $scope.options[0];
});;
});
The proper way to do it is using the ng-options directive. The HTML would look like this.
<select ng-model="selectedTestAccount"
ng-options="item.Id as item.Name for item in testAccounts">
<option value="">Select Account</option>
</select>
JavaScript:
angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
method: 'GET',
url: '/your-api-url',
}).success(function (result) {
$scope.testAccounts = result;
});
});
You'll also need to be sure that angular is run on your HTML and that your module is loaded.
<html ng-app="test">
<body ng-controller="DemoCtrl">
....
</body>
</html>
When I reload the page, the first option is always empty. I want the option containing text Any Make to be the default select option. Here is the code for my view:
<select class="form-control" id="make" name="make" ng-init="Any Make" ng-model="makeSelected" ng-change="makeChanged()">
<option value="0" selected="selected"> Any Make</option>
<option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option>
</select>
here is my controller code:
.controller("homeController", function ($scope, makeData, $http) {
$scope.makeData = makeData;
$scope.makeChanged = function () {
$http({
method: "GET",
url: "homeService.asmx/GetModelById"})
.then(function (response) {
$scope.modelData = response.data;
})
}
})
just remove ng-init and in your model give default value
$scope.makeSelected = 0;
Here is a running fiddle for your code Click here
Fiddle for code with dynamic data Click here
If you aren't going to use ngOptions, at least get rid of that ng-init since it isn't a function, and in the controller function set $scope.makeSelected = 0;
Then you can remove the selected="selected" on that initial option, since the angularJS code will be handling what is selected.
See a demonstration below:
angular.module('app', [])
.value('makeData', [{
"make_id": 1,
"make_name": "cat"
},{
"make_id": 2,
"make_name": "dog"
},{
"make_id": 6,
"make_name": "monkey"
}])
.controller("homeController", function($scope, makeData, $http) {
//initialize the value associated with ng-model on the select list
$scope.makeSelected = 0;
$scope.makeData = makeData;
$scope.makeChanged = function() {
console.log('makeChanged');
//$http() request removed because we don't have access outside this domain for AJAX requests.
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="homeController">
<select class="form-control" id="make" name="make" ng-model="makeSelected" ng-change="makeChanged()">
<option value="0"> Any Make</option>
<option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option>
</select>
<div>makeSelected: {{makeSelected}}</div>
</div>
I am trying to connect some functionality between controllers. Basically I want a div to hide/show based on what radio is selected in a different controller.
With a little help I managed to get this working part of the way. Here's what I have so far.
I set up a factory to bridge communication between the 2 controllers where I have an update function that is fired upon ng-change to update the string with the new desired one.
.factory("sessionCheck", function() {
var sessionCheck = {};
var update = function (index) {
console.log(index);
sessionCheck = index;
return sessionCheck;
};
return { update: update }
So in the first controller will call the function when ng-change occurs on the radios, like so:
//bring in session check, (injected above)
$scope.updateChecker = sessionCheck;
$scope.sessionChange = function(){
$scope.updateChecker.update($scope.opMeasure);
};
So this works fine if I console.log the index in the change function in the factory. So where I'm struggling is pulling this information into another controller and using it to ng-hide (or show) a div.
It would also be cool if there was a default value of "1" returning before the ng-change fired. It would be even better if there is an easier way that directly reads off of the radios' model (opMeasure) instead of firing off the ng-change of the radios.
Been struggling with this for a few hours, any help would be much appreciated. Thanks!!
I have answered a similar question yesterday. You can do this by sharing a common data object reference across your controllers using a common service.
DEMO
JAVASCRIPT
angular.module('demo', [])
.factory('SessionCheck', function() {
var sessionCheck = {
data: {}
};
// default value
sessionCheck.data.selection = 1;
return sessionCheck;
})
.controller('Ctrl1', function($scope, SessionCheck) {
$scope.data = SessionCheck.data;
})
.controller('Ctrl2', function($scope, SessionCheck) {
$scope.data = SessionCheck.data;
});
HTML
<div ng-controller="Ctrl1">
<h1>Controller 1</h1>
Measurement:
<select ng-model="data.selection">
<option value="">-- Select</option>
<option value="1">1 Meter</option>
<option value="2">2 Meters</option>
<option value="3">3 Meters</option>
</select>
</div>
<div ng-controller="Ctrl2">
<h1>Controller 2</h1>
<div ng-show="data.selection == 1">
1 Meter items
</div>
<div ng-show="data.selection == 2">
2 Meter items
</div>
<div ng-show="data.selection == 3">
3 Meter items
</div>
</div>
I have all controllers defined at one place.
$routeProvider.when(pages.hello,
{
templateUrl: 'test/hello.html',
controller: 'myController',
access: access.anon,
helloPage: 'arf'
});
My hello.html looks like this.
<select name="chooseFunc" data-ng-model="choosenFunction" class="input-xlarge ng-pristine ng-valid" data-ng-click="fetchID()" data-ng-change="update(choosenFunction)">
<option value="ABCD">ABCD</option>
<option value="CDEF">CDEF</option>
</select>
Now I want to call a http get method "/abc/hello" to populate the drop down like ABCD, CDEF values based on it.
I have written some thing like this.
$scope.fetchID = function() {
console.log("hello in fectch id");
$http.get('/abc/hello').success(successCallback).error(error);
};
My function is not getting called. Could some help me with the following.
Calling fecthID() function on page load.
fechID() function should populate the options in select element.
I am new here. Can some one help me.
I would write controller like:
function myController($scope,$http) {
$scope.values = [{id:"ABCD",Name:"David"},{id:"CDEF",Name:"John"}];
$scope.selectedItem = $scope.values[0].id;
$scope.fetchID = function() {
$http.get('/abc/hello').success(
function(data, status, headers, config){
$scope.values.push(data);// play here
})
.error(error);
};
$scope.fetchID(); // call
}
and hello.html with init first combo value:
<select name="chooseFunc"
ng-model="selectedItem"
ng-options="selectedItem.id as selectedItem.id for selectedItem in values"
class="input-xlarge ng-pristine ng-valid"
data-ng-click="fetchID()"
data-ng-change="update(choosenFunction)"
></select>
You can use ng-options to populate select like
<select ng-model="mySelecetdValue" ng-options="item for item in items">
</select>
To Call fecthID(), Just call it like
$scope.fetchID()
And Populate items in successCallback function