I am new to angularjs and trying to find a solution for the setting a selected value of radio group to the ngmodel.
//my.html
<div ng-controller='controller'>
<div class="btn-group" ng-model="option" ng-repeat="arr in dragDropOption">
<input type="radio" name="optionCorrectOpt" data-ng-model="option"
value="{{dragDropOption[$index].text}}">
{{dragDropOption[$index].text}}
</div>
and
//mycontroller.js
app = angular.module('app', []);
app.controller('controller', function ($scope) {
$scope.dragDropOption = [];
$scope.option = "not set";
$scope.dragDropOption = [{
text: "analog"
}, {
text: "isdn"
}, {
text: "dsl"
}];
// $scope.option = $scope.dragDropOption[0].text;
});
My fiddle is here!
Might be it is repeated question, please help me with sharing already answerd stackoverflow question's link or new answer. Thanks in advance.
For input change
data-ng-model="option"
to:
data-ng-model="$parent.option"
Demo Fiddle
Replace
$scope.option = "not set";
<input type="radio" name="optionCorrectOpt" data-ng-model="option"
value="{{dragDropOption[$index].text}}">
To:
$scope.radioOption = {};
$scope.radioOption.selected = "not set"
<input type="radio" name="optionCorrectOpt" data-ng-model="radioOption.selected"
value="{{dragDropOption[$index].text}}">
JS FIDDLE
Related
How can I execute a function when a check box is checked in angular js. I have seen a few answers on stack overflow regarding this but I cannot seem to implement them on my scenario
my code:
<div ng-controller="MyCtrl">
<div class="checkbox">
<label>
<input type="checkbox" ng-model="thirtyDay" ng-click="changeAxis()">
Last 30 Days
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="wholeTimeline" ng-click="changeAxis()">
Whole Timeline
</label>
</div>
</div>
js.
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
function changeAxis(){
if ($scope.thirtyDay) {
alert("checked 30");
}
else if($scope.wholeTimeline) {
alert("checked whole");
}
};
}
You need to place the function on the $scope, so the view will recognize it:
$scope.changeAxis = function() {
if (!$scope.thirtyDay) {
alert("checked 30");
}
else if(!$scope.wholeTimeline) {
alert("checked whole");
}
};
Another thing to notice is that when entering the function you'll get the value of the model from before the push. So if you click and it's checked, the value will still be false (hasn't been updated yet). So either use !$scope.thirtyDay or place in a $timeout.
EDIT: As Mike correctly mentioned in his comment, you would probably be better of using ng-change instead of ng-click (this way the other property won't trigger as well when interacting with the other one). I would also join the recommendation and suggest considering a different function for different properties, but I'm not sure exactly to which use you're doing this.
Here is working demo
HTML
<div ng-app="myApp">
<div ng-controller="myCtrl" >
<div class="checkbox">
<label>
<input type="checkbox" ng-model="thirtyDay" ng-change="changeAxis1()">
Last 30 Days
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="wholeTimeline" ng-change="changeAxis2()">
Whole Timeline
</label>
</div>
</div>
</div>
JS
var app = angular.module('myApp', []);
app.controller('myCtrl',['$scope', function($scope) {
$scope.changeAxis1 = function() {
if ($scope.thirtyDay) {
alert("checked 30");
$scope.wholeTimeline = false;
}
};
$scope.changeAxis2 = function() {
if($scope.wholeTimeline) {
alert("checked whole");
$scope.thirtyDay = false;
}
};
}]);
You need to add controller to myApp with this line.
myApp.controller('MyCtrl', MyCtrl);
You need to link changeAxis function to scope
$scope.changeAxis = changeAxis;
So your app.js will be something like
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', MyCtrl);
function MyCtrl($scope) {
function changeAxis(){
if ($scope.thirtyDay) {
alert("checked 30");
}
else if($scope.wholeTimeline) {
alert("checked whole");
}
};
$scope.changeAxis = changeAxis;
}
I hope you have added ng-app to your html. Also please consider the ngChange suggestion mentioned in the other answer.
I want to do something like this
<input type="checkbox" ng-model="first" ng-click="chkSelect()"/><label>First</label>
<input type="checkbox" ng-model="second" ng-click="chkSelect()"/><label>Second</label>
<input type="checkbox" ng-model="third" ng-click="chkSelect()"/><label>Third</label>
<input type="checkbox" ng-model="forth" ng-click="chkSelect()"/><label>Forth</label>
<button>Selected</button>
On button click I want to display selected checkbox labelname.
$scope.chkSelect = function (value) {
console.log(value);
};
Because the checkboxes are mapped, you can reference $scope.first, $scope.second, etc in your chkSelect() function. It's also possible to have a set of checkboxes mapped as a single array of data instead of having to give each checkbox a name. This is handy if you are generating the checkboxes, perhaps from a set of data.
I agree with Bublebee Mans solution. You've left out a lot of detail on why you're trying to get the label. In any case if you REALLY want to get it you can do this:
$scope.chkSelect = function (value) {
for(var key in $scope){
var inputs = document.querySelectorAll("input[ng-model='" + key + "']");
if(inputs.length){
var selectedInput = inputs[0];
var label = selectedInput.nextSibling;
console.log(label.innerHTML);
}
};
};
You can mess around with it to see if it's indeed selected.
fiddle: http://jsfiddle.net/pzz6s/
Side note, for anybody who knows angular please forgive me.
If you are dealing with server data, you might need isolated html block and deal with data in controller only.
You can do it by creating array in controller, maybe your data from response, and use ngRepeat directive to deal independently in html code.
Here is what I am telling you:
HTML:
<form ng-controller="MyCtrl">
<label ng-repeat="name in names" for="{{name}}">
{{name}}
<input type="checkbox"
ng-model="my[name]"
id="{{name}}"
name="favorite" />
</label>
<div>You chose <label ng-repeat="(key, value) in my">
<span ng-show="value == true">{{key}}<span>
</label>
</div>
</form>
Javascript
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.names = ['pizza', 'unicorns', 'robots'];
$scope.my = { };
}
You want to have something like the following in your controller (untested, working from memory):
$scope.checkBoxModels = [ { name: 'first', checked: false }, { name: 'second', checked: false }, { name: 'third', checked: false }, { name: 'fourth', checked: false } ];
Then in your view:
<input ng-repeat"checkboxModel in CheckBoxModels" ng-model="checkBoxModel.checked" ng-click="chkSelect(checkBoxModel)" /><label>{{checkBoxModel.name}}</label>
Then update your function:
$scope.chkSelect = function (checkBoxModel) {
console.log(checkBoxModel.name);
};
I have 2 forms - a billing and a shipping. If the user checks a checkbox, the shipping address should be populated with the billing address and turn disabled. If the user unchecks the box, the shipping address should be blank and return to enabled.
I have this working right now with $watch but it feels hacky. I have 2 $watches nested in eachother watching the same element. I want to know if there is a better way to achieve what I am doing.
I tried using a ternary operator in the ng-model like below but that didn't work either.
<input ng-model="isSameAsBilling ? billName : shipName" ng-disabled="isSameAsBilling" />
A plunkr of my "working" code
HTML:
<input ng-model="billName" />
<input type="checkbox" ng-checked="isSameAsBilling" ng-click="sameAsBillingClicked()"/>
<input ng-model="shipName" ng-disabled="isSameAsBilling" />
JavaScript:
$scope.isSameAsBilling = false;
$scope.sameAsBillingClicked = function(){
$scope.isSameAsBilling = !$scope.isSameAsBilling;
};
$scope.$watch('isSameAsBilling', function(isSame){
if ($scope.isSameAsBilling) {
var shipNameWatcher = $scope.$watch('billName', function (newShipName) {
$scope.shipName = $scope.billName;
var secondBillWatcher = $scope.$watch('isSameAsBilling', function(isChecked){
if (!isChecked){
shipNameWatcher();
secondBillWatcher();
$scope.shipName = '';
}
});
});
}
});
I think I've finally got what you're after here.
When the checkbox is checked, it registers a $watch on the billName and mirrors it to the shipName.
When the checkbox is unchecked, the deregisters the $watch and clears the shipName
angular
.module('app', [])
.controller('appController', ['$scope', function($scope){
$scope.isSameAsBilling = false;
$scope.isSameChanged = function() {
if ($scope.isSameAsBilling) {
// register the watcher when checked
$scope.nameWatcher = $scope.$watch('billName', function(bName) {
$scope.shipName = bName
})
} else {
// deregister the watcher and clear the shipName when unchecked
$scope.nameWatcher();
$scope.shipName = ''
}
}
}]);
and here is the PLUNK
I'm new to Angular and am trying to capture the selected radio value but the documentation is not clear when using ng-repeat. Any help would be greatly appreciated.
<div ng-repeat="item in ed">
<label for="{{item['code']}}">
<input ng-change="getPlanTypes()" ng-model="ed" type="radio" id="{{item['code']}}" name="effective_date" value="{{item['code']}}">
{{item['date']}} </label>
</div>
Here is the controller but I'm unsure of the right way to get the selected radio value?
rates.controller('getEffectiveDates',
function($scope, $http, $location, myService, localStorageService) {
myService.effective_dates().then(function(ed) {
$scope.ed = ed;
});
$scope.getPlanTypes = function() {
console.log($scope.ed['code']); //Futile attempt that returns undefined
localStorageService.add('code',$scope.ed['code']);
$location.path("/plan-types");
}
});
Do
ng-click="getPlanTypes(item.code)"
and in your controller, you can get the value
$scope.getPlanTypes = function (ed) {
console.log(ed);
}
http://jsfiddle.net/2LZpv/
The HTML
<div ng-app="myApp" ng-controller="getEffectiveDates">
<div ng-repeat="item in ed">
<label for="{{item['code']}}">
<input ng-click="getPlanTypes(item)" ng-model="ed" type="radio" id="{{item['code']}}" name="effective_date" value="{{item['code']}}"/>
{{item['date']}} </label>
</div>
</div>
The JS
angular.module("myApp",[]).controller('getEffectiveDates', ["$scope", function($scope) {
$scope.ed = [{code:'1',date:"test date 1"},{code:'2',date:"test date 2"}];
$scope.getPlanTypes = function(selectedItem) {
console.log(selectedItem["code"]); //Feeble attempt that returns undefined
}
}]);
I'm trying to generate a set of check-boxes from an object array. I'm aiming to have the check-boxes dynamically map their ng-model to a property of the new object that will be submitted into the array.
What I had in mind is something like
<li ng-repeat="item in items">
<label>{{item.name}}</label>
<input type="checkbox" ng-model="newObject.{{item.name}}">
</li>
This doesn't work as can be seen on this JSFiddle:
http://jsfiddle.net/GreenGeorge/NKjXB/2/
Can anybody help?
This should give you desired results:
<input type="checkbox" ng-model="newObject[item.name]">
Here is a working plunk: http://plnkr.co/edit/ALHQtkjiUDzZVtTfLIOR?p=preview
EDIT
As correctly noted in the comments using this with ng-change requires a "dummy" ng-model to be present beforehand. It should however be noted that apparently with 1.3 the required options have been provided by the framework. Please check out https://stackoverflow.com/a/28365515/3497830 below!
/EDIT
Just in case you are like me stumbling over a simple case while having a more complex task, this is the solution I came up with for dynamically binding arbitrary expressions to ng-model: http://plnkr.co/edit/ccdJTm0zBnqjntEQfAfx?p=preview
Method: I created a directive dynamicModel that takes a standard angular expression, evaluates it and links the result to the scope via ng-model and $compile.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = {};
$scope.testvalue = 'data.foo';
$scope.eval = $scope.$eval;
});
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = {};
$scope.testvalue = 'data.foo';
$scope.eval = $scope.$eval;
});
app.directive('dynamicModel', ['$compile', function ($compile) {
return {
'link': function(scope, element, attrs) {
scope.$watch(attrs.dynamicModel, function(dynamicModel) {
if (attrs.ngModel == dynamicModel || !dynamicModel) return;
element.attr('ng-model', dynamicModel);
if (dynamicModel == '') {
element.removeAttr('ng-model');
}
// Unbind all previous event handlers, this is
// necessary to remove previously linked models.
element.unbind();
$compile(element)(scope);
});
}
};
}]);
Usage is simply dynamic-model="angularExpression" where angularExpression results in a string that is used as the expression for ng-model.
I hope this saves someone the headache of having to come up with this solution.
Regards,
Justus
With Angular 1.3, you can use ng-model-options directive to dynamically assign the model, or bind to an expression.
Here is a plunkr: http://plnkr.co/edit/65EBiySUc1iWCWG6Ov98?p=preview
<input type="text" ng-model="name"><br>
<input type="text" ng-model="user.name"
ng-model-options="{ getterSetter: true }">
More info on ngModelOptions here: https://docs.angularjs.org/api/ng/directive/ngModelOptions
This is my approach to support deeper expression, e.g. 'model.level1.level2.value'
<input class="form-control" ng-model="Utility.safePath(model, item.modelPath).value">
where item.modelPath = 'level1.level2' and
Utility(model, 'level1.level2') is the utility function that returns model.level1.level2
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form name="priceForm" ng-submit="submitPriceForm()">
<div ng-repeat="x in [].constructor(9) track by $index">
<label>
Person {{$index+1}} <span class="warning-text">*</span>
</label>
<input type="number" class="form-control" name="person{{$index+1}}" ng-model="price['person'+($index+1)]" />
</div>
<button>Save</button>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.price = [];
$scope.submitPriceForm = function () {
//objects be like $scope.price=[{person1:value},{person2:value}....]
console.log($scope.price);
}
});
</script>
</body>
</html>