I create customdirective and want to ng-model update before ng-change fire. Currently ng-change fire before udpate ng-mdoel value below is my code.
Main issue is coming when i change page number in dropdown list. It alert with previous value. I think ng-mdoel update after ng-change fire. but i want ng-model fire before ng-change.
app.directive('bottomPagination', function () {
var directive = {
templateUrl: '/App/Common/directives/bottomPagination.html',
restrict: 'A',
replace: true,
scope: {
currentPage: '=',
changePageSize: '&'
}
};
return directive;
});
//here is html directive (/App/Common/directives/bottomPagination.html)
<select id="pagesizeddl" ng-model="pageSize" ng-change="changePageSize()">
<option>5</option>
<option>10</option>
<option>20</option>
<option>30</option>
</select>
// here is my html page where i used directive
<div data-ng-controller="ProductsList as vm">
<div data-bottom-pagination
data-page-size="vm.paging.pageSize"
data-change-page-size="vm.changePageSize()"
>
</div>
</div>
// This is contrller
(function () {
// Start Products List function
var ListControllerId = 'ProductsList';
angular.module('app').controller(ListControllerId,
['$scope', ListController]);
function ListController($scope) {
var vm = this;
vm.paging = {
pageSize: 10
};
vm.changePageSize = changePageSize;
function changePageSize() {
alert(vm.paging.pageSize);
}
}
})();
Hi I recently had the same problem.
My best practice solution is to add a parameter in the ng-change function in your directive template. You need to add the parameter as an JSON Object!
<select id="pagesizeddl" ng-model="pageSize" ng-change="changePageSize({pageSize:pageSize})">
<option>5</option>
<option>10</option>
<option>20</option>
<option>30</option>
</select>
The property "pageSize" (of the JSON Object) will be matched with the parameter of your directive function vm.changePageSize(pageSize). So it is necessary that both have the same name!
<div data-ng-controller="ProductsList as vm">
<div data-bottom-pagination
data-page-size="vm.paging.pageSize"
data-change-page-size="vm.changePageSize(pageSize)"
>
</div>
Now you only have to alter your controller function like this:
function changePageSize(pageSize) {
alert(pageSize);
}
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.
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 perform a case-insensitive bind of an ng-model to a dynamic select drop-down using AngularJS.
by going through various other relavent answers from stack over flow, i have come up with something like below on the view , here caseinsensitive-options is an directive which i have come up with referencing the following solution
AngularJS case-insensitive binding to a static select drop-down
HTML:
<select id="dcName" caseinsensitive-options="" ng-model="DC.name" class="form-control">
<option value="">--- Please Select ---</option>
<option ng-repeat="dataCenter in inventoryDataCenters" value="{{dataCenter}}">{{dataCenter}}</option>
</select>
js directive code :
app.directive('caseinsensitiveOptions', function() {
return {
restrict: 'A',
require: ['ngModel', 'select'],
link: function(scope, el, attrs, ctrls) {
var ngModel = ctrls[0];
ngModel.$formatters.push(function(value) {
var option = [].filter.call(el.children(), function(option) {
return option.value.toUpperCase() === value.toUpperCase()
})[0];
return option ? option.value : value
});
}
}
});
The expected result is
when i pass something like this for
$scope.inventoryDataCenters = ["TEST1","test2",teST3]; and ng-model for DC.name has value TesT1.
The drop down should show TEST1 by doing case insensitive binding. That doesnt happen now. The above solution works perfect when we have static drop down.
things to be considered is that the select is inside a div which ng-repeat as shown below
ng-repeat="DC in workflowData.project_data.service_info.variables.service_data['data-center']"
and ng-model for select DC.name is derived from the above array DC.
check this URL for binding based on case insensitive value
https://jsfiddle.net/dwd2du17/6/
<div ng-app="module" ng-controller="controller as ctrl">
<select id="animal" ng-model="ctrl.animal">
<option value="">--- Select ---</option>
<option value="CaT">Cat</option>
<option value="DOg">Dog</option>
</select>
{{ctrl.animal}}
</div>
var appForm = angular.module('module', [])
.controller('controller', function($scope) {
});
I am exploring advanced features in AngularJS such as custom directives. I want to have a textbox which by using custom directive should allow either numbers only or text only depending upon the value chosen by the user from a dropdown box. I have managed to create a custom directive which allows numbers only based upon AngularJs Custom Directive fails the text box validation . I am not sure how to apply a custom directive dynamically to the same textbox. I have create another custom directive which allows text only, but not sure how to replace the number only directive with the text only directive dynamically.
<body>
<div ng-app="TextboxExample" ng-controller="ExampleController">
<form name="shippingForm" novalidate>
<select id="textBoxOptions" >
<option value="number" selected="selected">Numbers Only</option>
<option value="text">Text Only</option>
<option value="special">Special Characters</option>
<option value="any">Any Value</option>
</select>
<input id="customTextBox" unbindable number-only-input type="text" name="name" ng-model="testvalue.number" required />
<span class="error" ng-show="shippingForm.name.$error.required">
Please enter a value
</span>
</form>
</div>
<script src="scripts/angular.js"></script>
<script src="scripts/jquery.min.js"></script>
<script>
$("select").change(function () {
var selected = $("#textBoxOptions").val();
$('#customTextBox').attr("ng-model", selected);
});
</script>
<script>
angular.module('TextboxExample', [])
.controller('ExampleController', ['$scope', function ($scope) {
$scope.testvalue = { number: 1, validity: true };
}])
.directive('numberOnlyInput', ['$compile', function ($compile) {
return {
link: function (scope, element, attrs) {
var watchMe = attrs["ngModel"];
scope.$watch(watchMe, function (newValue, oldValue) {
if (newValue == undefined || newValue == null || newValue == "") {
return;
} else if (isNaN(newValue)) {
var myVal = watchMe.split(".");
switch (myVal.length) {
case 1:
scope[myVal[0]] = oldValue;
break;
case 2:
scope[myVal[0]][myVal[1]] = oldValue;
}
}
$compile(element)(scope);
});
}
};
}]);
</script>
When I change the value in the dropdown box, it correctly changes the ng-model on customTextBox as checked by inspect element. However, I am not sure how to create and apply multiple directives. Thanks
There are several possibilities. You can switch directive atttibute or whole elements:
<input {{ yourmode ? number-directive : text-directive }} ng-model="data">
or
<input ng-show="yourmode" number-directive ng-model="data">
<input ng-show="!yourmode" text-directive ng-model="data">
or you change the mode with dynamic directive attributes
<input directive-data="yourmode" my-input-directive ng-model="data">
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>