I am trying to get selected radio button value using below code but i am getting undefined value. what is my mistake?
html
<form name="form" class="form-horizontal" role="form">
<!-- RADIO BUTTONS -->
<div class="form-group">
<label class="col-sm-2 control-label">Clouds</label>
<div class="col-sm-6">
<label class="radio-inline" ng-repeat="option in entity.fields">
<input type="radio" ng-model="data" name="option.name" value="{{option.id}}">
{{option.name}}
</label>
</div>
</div>
<br />
<button type="submit" id="submit" ng-click="save(data)">Submit</button>
<br />
</form>
controller
routerApp.controller('DynamicController2', ['$scope', function ($scope) {
// we would get this from the api
$scope.entity = {
name: "my favorite fruits",
fields:
[{ id: 1, name: "orange" }, { id: 2, name: "pink" }, { id: 3, name: "gray" }, { id: 4, name: "cyan" }]
};
$scope.save = function (data) {
alert(data);
}
}]);
The variable 'data' used in ng-modal is not defined in the controller. You need to define 'data' variable as $scope. Then there's no need to pass the variable to the function save.
here how your controller should be
routerApp.controller('DynamicController2', ['$scope', function ($scope) {
// we would get this from the api
$scope.data;
$scope.entity = {
name: "my favorite fruits",
fields:
[{ id: 1, name: "orange" }, { id: 2, name: "pink" }, { id: 3, name: "gray" }, { id: 4, name: "cyan" }]
};
$scope.save = function () {
alert($scope.data);
}
}]);
And your button in html should be like :
<button type="submit" id="submit" ng-click="save()">Submit</button>
Hopefully this will solve your problem.
Related
<div class="district-list" ng-repeat="office in offices | filter : {'DisplayOffice' : officeLocationLevelList.searchText}|limitTo:1">
Have a multilevel list of data. depending on the condition i want to filter the data.(First Level/ inner level). If the first level is selected then i have to search with one json attribute and if the inner level is selected then search with another json attribute. I have set it in a scope variable. How can use scope variable instead of 'DisplayOffice'
you can bind a function to filter which returns the filter condition using scope variables.
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.data = [
{
id: 1,
name: 'name1'
},{
id: 2,
name: 'name2'
},{
id: 3,
name: 'name3'
},{
id: 3,
name: 'aaaaa'
}
];
$scope.getCondition = function() {
var obj = {};
obj[$scope.key] = $scope.value;
return obj;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
Key: <input type="text" ng-model="key">
Value: <input type="text" ng-model="value">
<div ng-repeat="item in data | filter: {[key]:value}">
{{item.name}}
</div>
</div>
and there is another way while using ES6' new feature {[key]: value}, but this may now work for some browsers.
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.$watch("key", function() {
console.log({[$scope.key]:$scope.value});
});
$scope.$watch("value", function() {
console.log({[$scope.key]:$scope.value});
});
$scope.data = [
{
id: 1,
name: 'name1'
},{
id: 2,
name: 'name2'
},{
id: 3,
name: 'name3'
},{
id: 3,
name: 'aaaaa'
}
];
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
Key: <input type="text" ng-model="key">
Value: <input type="text" ng-model="value">
<div ng-repeat="item in data | filter: {[key]: value}">
{{item.name}}
</div>
</div>
I am trying to generate a HTML form with angularjs ngRepeat. I load a JSON file that contains the fields of desired form and save this object in my $scope. I have a ngRepeat element that generates form inputs based on the JSON object.
The problem is when I print $scope.<myFormName> it just have one field name "{{header.name}}" as I expect some fields based on my JSON model.
Actually I see the form generated in HTML properly but the same thing does not happen in angular scope.
angular.module("myApp",[])
.controller("myCtrl",["$scope",function($scope){
// In this funtion I Set fields of form and make my model empty
$scope.getHeaders = function () {
console.info('getHeaders');
$scope.headersForCreation = [
{
name: 'givenName',
type: 'string',
caption: "nameAndFamily"
},
{
name: 'userName',
type: 'string',
caption: "userName"
},
{
name: 'password',
type: 'password',
caption: "password"
},
{
name: 'passwordConfirm',
type: 'password',
caption: "passwordConfirm"
},
{
name: 'mail',
type: 'string',
caption: "email"
},
{
name: 'mobile',
type: 'string',
caption: "mobile",
regex: '0[1-9][0-9]{9}'
}
];
$scope.userInputsInCreation = {};
angular.forEach($scope.headersForCreation, function (headerItem, key) {
$scope.userInputsInCreation[headerItem.name] = '';
});
}; // end of get header
$scope.getHeaders();
console.log($scope.createForm)
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl" id="add-container-access" ng->
<form class="form-horizontal" name="createForm" init="getHeaders()">
<div class="form-group" ng-repeat="header in headersForCreation" >
<label for="id-{{header.name}}" class="col-sm-4 control-label">
{{header.caption}}: </label>
<div class="col-sm-8"
ng-class="{'has-error': createForm.{{header.name}}.$error.$invalid }">
<input type="header.type" class="form-control"
name="{{header.name}}" ng-required="{{header.notNull}}"
id="id-{{header.name}}"
ng-model="userInputsInCreation[header.name]" >
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<button class="btn btn-default" >
ADD
<i class="glyphicon glyphicon-plus-sign"></i>
</button>
</div>
</div>
</form>
</div>
Because your controller initialized before AngularJS form directive.
angular.module("myApp",[])
.controller("myCtrl",["$scope","$timeout",function($scope, $timeout){
// In this funtion I Set fields of form and make my model empty
$scope.getHeaders = function () {
console.info('getHeaders');
$scope.headersForCreation = [
{
name: 'givenName',
type: 'string',
caption: "nameAndFamily"
},
{
name: 'userName',
type: 'string',
caption: "userName"
},
{
name: 'password',
type: 'password',
caption: "password"
},
{
name: 'passwordConfirm',
type: 'password',
caption: "passwordConfirm"
},
{
name: 'mail',
type: 'string',
caption: "email"
},
{
name: 'mobile',
type: 'string',
caption: "mobile",
regex: '0[1-9][0-9]{9}'
}
];
$scope.userInputsInCreation = {};
angular.forEach($scope.headersForCreation, function (headerItem, key) {
$scope.userInputsInCreation[headerItem.name] = '';
});
}; // end of get header
$scope.getHeaders();
$timeout(function(){ console.log($scope.createForm); });
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl" id="add-container-access" ng->
<form class="form-horizontal" name="createForm" init="getHeaders()">
<div class="form-group" ng-repeat="header in headersForCreation" >
<label for="id-{{header.name}}" class="col-sm-4 control-label">
{{header.caption}}: </label>
<div class="col-sm-8"
ng-class="{'has-error': createForm.{{header.name}}.$error.$invalid }">
<input type="header.type" class="form-control"
name="{{header.name}}" ng-required="{{header.notNull}}"
id="id-{{header.name}}"
ng-model="userInputsInCreation[header.name]" >
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<button class="btn btn-default" >
ADD
<i class="glyphicon glyphicon-plus-sign"></i>
</button>
</div>
</div>
</form>
</div>
Simple problem, probably discussed many times, but I can't find a proper solution on this simple issue.
The problem:
Why are the Daltons selectable, but the selected Daltons don't show up in the select-element?
Controller:
var myApp = angular.module('myApp', ['ui.select2']);
function MyCtrl($scope) {
$scope.daltons = [
{ id: 10, name: 'Joe' },
{ id: 20, name: 'William' },
{ id: 30, name: 'Jack' },
{ id: 40, name: 'Averell' },
{ id: 50, name: 'Ma' }
];
$scope.selectedDaltons = [40]; // Averell is preselected
};
View:
<div ng-controller="MyCtrl">
<label for="1">Please select items:</label>
<select id="1"
ui-select2
multiple
ng-model='selectedDaltons'
ng-options="dalton.id as dalton.name for dalton in daltons">
</select>
<label for="2">Selected Items:</label>
<ul id="2">
<li ng-repeat="dalton in selectedDaltons">{{dalton}}</li>
</ul>
</div>
Here it is as a jsfiddle
I think the issue is that ng-options is not supported in ui-select2. I reworked your fiddle using the option tag with an ng-repeat:
http://jsfiddle.net/u48j0yyc/1/
<div ng-controller="MyCtrl">
<label>Please select items:</label>
<select ui-select2 multiple ng-model='selectedDaltons'>
<option ng-repeat="d in daltons" ng-bind="d.name" value="{{ d.id }}"></option>
</select>
<label>Selected Items:</label>
<ul>
<div ng-bind="selectedDaltons"></div>
</ul>
</div>
var myApp = angular.module('myApp', ['ui.select2']);
function MyCtrl($scope) {
$scope.daltons = [
{ id: 10, name: 'Joe' },
{ id: 20, name: 'William' },
{ id: 30, name: 'Jack' },
{ id: 40, name: 'Averell' },
{ id: 50, name: 'Ma' }
];
$scope.selectedDaltons = [40]; // Averell is preselected
};
*This is my html file where i want to repeat chapters which is a array that looks like
My code gives binds the selected checked boxes only (Index values) to true. But i need the entire list of chapters and their i.d's to be retrieved on submit.
Cannot figure out how to iterate it on nested loops *
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<span ng-repeat="chapter in chapters">
<label><input type="checkbox" name="checkbox" value="{{chapter}} ng-model="escConfigForm.chapters[$index]" >{{chapter.name}}</label><br>
</span>
<input type="submit" id="save" value="Save" />
$scope.chapters = chapterService.getChapters($scope.isbn);
$scope.submit = function(escConfigForm) {
var postData = {
content_items: JSON.stringify({
"#context" : [],
"#graph" : [ {
"#type" : "ContentItemPlacement",
"placementOf" : {
"#type" : "LtiLink",
"text" : escConfigForm.examName,
"mediaType" : "application/vnd.ims.lti.v1.launch+json",
"title" : "Exam Study Center",
"custom" : {
"dueDate" : escConfigForm.examDueDate,
"targetScore" : escConfigForm.examTargetScore,
"chapters" : escConfigForm.chapters
},
"activityType" : "other",
"activityRefId" : $scope.escId
}
} ]
}),
data: $scope.data
};
postForm($scope.postUrl, postData);
var configData = {
"activityRefId" : $scope.escId,
"dueDate" : escConfigForm.examDueDate,
"targetScore" : escConfigForm.examTargetScore,
"chapters" : escConfigForm.chapters
};
console.log($scope.chapters);
JSON file:
[{"name":"Chapter 1: Negative Messages","id":"832115"},{"name":"Chapter 2: Physics","id":"832115"},...]
I would recommend maintaining a list of the selected objects in the controller.
using this post as referenece: How do I bind to list of checkbox values with AngularJS?
I created this fiddle: http://jsfiddle.net/ruwk5r0v/7/
<div ng-app="formExample">
<div ng-controller="ExampleController"> <span ng-repeat="chapter in chapters" ng-click="checkboxChange($index)" ng-checked="selection.indexOf($scope.chapters[$index]) > -1">
<input type="checkbox" name="checkbox" value="{{$index}}" />
{{chapter.name}}
<br>
</span>
<br>
<input type="submit" ng-click="submitForm()" id="save" value="Save" />
<div> <span ng-repeat="chapter in selection">
<span>
{{chapter.name}}
</span>
<br>
</div>
and the js:
angular.module('formExample', []).controller('ExampleController', ['$scope', function ($scope) {
$scope.chapters = [{
"name": "Chapter 1: Negative Messages",
"id": "832115"
}, {
"name": "Chapter 2: Physics",
"id": "832115"
}];
$scope.submitForm = function () {
console.log(selection);
}
$scope.selection = []
$scope.checkboxChange = function(index){
var chapter = $scope.chapters[index];
var idx = $scope.selection.indexOf(chapter);
if (idx > -1){
$scope.selection.splice(idx, 1);
} else {
$scope.selection.push(chapter);
}
}
}]);
here you can very easily implement your submit function, just use the new selection object.
This really should be moved into a directive, but don't have time to write that right now :P
Here I created a controller for the snippet, and added some data to $scope.chapters object, and it is displaying correctly. The values disappear when selected, but that is another issue.
angular.module('myApp', [])
.controller('myCtrl', ['$scope',
function($scope) {
$scope.chapters = [{
name: 'Chapter 1: Negative Messages',
id: "1",
isSelected: false
}, {
name: 'Chapter 2: Physics',
id: "2",
isSelected: false
}];
$scope.submitItems = function(chapters) {
alert(JSON.stringify(chapters));
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<span ng-repeat="chapter in chapters">
<input type="checkbox" name="checkbox" value="{{chapter}}"
ng-model="chapter.isSelected" />
{{chapter.name}}
</span>
<br>
<form ng-submit="submitItems(chapters)">
<input ng-model="chapters" type="submit" id="save" value="Save" />
</form>
</div>
</div>
Edit: Updated the code to reflect the OP needs.
i wona get price and name of chosen radio buttons. its easy with simple html tags.
But I stacked when i trying generate radio buttons via angularjs from array (items)
Help!
http://jsfiddle.net/hanze/j9x23apu/
html
<h1>Select </h1>
<div ng-app="" ng-controller="OrderCtrl">
<div ng-repeat="item in items">
<div class="radio">
<label>
<input type="radio" name="item" ng-model="item" ng-checked="{{item.checked}}">
{{item.name}} +{{item.price}} $.</label>
</div>
</div>
Your choice: {{}} **what i must write here?**
<br>
Price: {{}} **and here?**
</div>
js
OrderCtrl = function ($scope) {
$scope.items = [{
name: 'None',
value: "no",
price: 0,
checked: true
}, {
name: 'Black',
value: "black",
price: 99,
checked: false
}, {
name: 'White',
value: "white",
price: 99,
checked: false
}, {
name: 'Barhat',
value: "barhat",
price: 49,
checked: false
}, {
name: 'Barhat',
value: "cream",
price: 49,
checked: false
}]
You can look at the angularjs documentaion about radio buttons here. You don't need to use ng-checked here. Use ng-value to set the value when redio is selected.
I changed your jsfiddle post.
Your are missing the closing tag for your input. And when you have ng-repeat you have a seperate scope. In this case you need $parent.selectedItem to hold your selected elements.
I have updated the JSFiddle with a working state solution.
<div ng-app="" ng-controller="OrderCtrl">
<div ng-repeat="item in items" style="text-indent: 30px">
<input type="radio" name="itemRadio" ng-model="$parent.selectedItem" ng-value="item.name"/>
{{item.name + '-' + item.price}}$.
</div>
Your choice: {{selectedItem}}
</div>
jsFiddle: http://jsfiddle.net/j9x23apu/16/
html
<div ng-app="" ng-controller="OrderCtrl">
<div ng-repeat="item in items" style="text-indent: 30px">
<label>
<input type="radio" name="item" ng-checked="{{item.checked}}" ng-click="change_item($event)" item-name="{{item.name}}" item-price="{{item.price}}" /> {{item.name}} + {{item.price}}
</label>
</div>
Your choice: {{selectedName}}
<br />
Price: {{selectedPrice}}
</div>
js
OrderCtrl = function ($scope) {
$scope.change_item = function(e) {
$scope.selectedName = e.target.attributes['item-name'].value;
$scope.selectedPrice = e.target.attributes['item-price'].value;
};
$scope.items = [{
name: 'None',
value: "no",
price: 0,
checked: true
}, {
name: 'Black',
value: "black",
price: 99,
checked: false
}, {
name: 'White',
value: "white",
price: 99,
checked: false
}, {
name: 'Barhat',
value: "barhat",
price: 49,
checked: false
}, {
name: 'Barhat',
value: "cream",
price: 49,
checked: false
}]
}