Form name could not identify on Angular JS validation - angularjs

I have a problem on my code. After submitting the form I have a function for validation checking but it seems that the condition on my function won't identify my form name. Here's my code:
Template form part:
<div class="modal-body">
<form name="form.addeditcoursewareModal">
<div class="row">
<div class="small-12 medium-12 large-12 columns">
<label class="stacked">
Question
<input name="question" type="text" class="form-field" placeholder="Question" ng-model="$ctrl.question.data.attributes.question" >
</label>
</div>
</div>
<div class="row">
<div class="small-12 medium-6 large-6 columns">
<label class="stacked">
Question Type: {{ $ctrl.question.data.attributes.question_type }}
<select name="question_type" class="form-field" id="questionType" ng-model="$ctrl.question.data.attributes.question_type" ng-change="$ctrl.getSelectedQuestionType()">
<option value="single">Single</option>
<option value="multiple">Multiple</option>
<option value="true_or_false">True or False</option>
<option value="free_text">Free Text</option>
</select>
</label>
</div>
Validation part:
validateForm(){
this.validatingForm = true;
if (this.question.data.attributes.question_type === 'true_or_false'){
this.question.data.attributes.choices.data[0].attributes.choice = 'True';
this.question.data.attributes.choices.data[1].attributes.choice = 'False';
}
if (this.modalOptions.actionType == 'duplicate'){
this.question.data.attributes.choices.data.forEach((value) => {
delete value.id;
});
}
if (this.modalOptions.type === 'multiple'){
this.validateCheckbox();
}
console.log(this);
if (this.form.addeditcoursewareModal.$invalid || this.invalidMultiple) { // ERROR DETECTED
// Check for an invalid field
angular.forEach(this.form.addeditcoursewareModal.$error, (field) => {
angular.forEach(field, (errorField) => {
if (errorField.$name === 'dynamicForm'){
errorField.dynamicInput.$setTouched();
} else {
// Set field as touched to display invalid field message
if (errorField.$name === 'single') {
this.invalidRadio = true;
}
errorField.$setTouched();
}
});
});
this.validatingForm = false;
} else {
Here's the error I got:
angular.js:14791 TypeError: Cannot read property 'addeditcoursewareModal' of undefined
I already tried renaming my form but the error is the same.

It seems that you are using the controller as syntax. You would need to add $ctrl in front of form.addeditcoursewareModal.
<form name="$ctrl.form.addeditcoursewareModal">

Related

Dropdown onchange textarea enable and disable in Angularjs

This question already asked but that is not solving my issue.
I want to enable and disable text-area when drop-down change. I tried some code but showing error.
TypeError: Cannot set property 'disabled' of undefined
at Scope.$scope.firstUsageChange (addcoupon.js:130)
addcoupon.html
<div class="col-sm-4">
<label>First Usage<code>*</code></label>
<select class="form-control" name="first_usage" ng-model="formData.first_usage" ng-change="firstUsageChange()" ng-required="true">
<option value="">Select First Usage</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div class="col-sm-4">
<label>First Usage Title<code>*</code></label>
<textarea class="form-control" name="first_usage_title" ng-model="formData.first_usage_title" ng-disabled="disabled" ng-required="true"></textarea>
</div>
addcoupon.js
$scope.firstUsageChange = function () {
$scope.result = $scope.formData.first_usage;
if($scope.result == 'yes')
{
$scope.first_usage_title.disabled= false;
}
else
{
$scope.first_usage_title.disabled= true;
}
//console.log();
};
in the html part:
<textarea class="form-control" name="first_usage_title" ng-
model="formData.first_usage_title" ng-disabled="disabled" ng-required="true">
</textarea>
try changing ng-disabled by:
ng-disabled="first_usage_title.disabled"
I got the result i just change $scope data $scope.disabled = true;
$scope.firstUsageChange = function () {
$scope.result = $scope.formData.first_usage;
if($scope.result == 'yes')
{
$scope.disabled = true;
}
else
{
$scope.disabled = false;
}
};

After uncheck the checkbox value is not inserted in mvc application

I have one checkbox and one textbox, now when I check the checkbox and write text in textbox at that time checkbox value and textbox value is inserted, but when I am uncheck the checkbox and write the text in textbox at that time textbox value is not inserted in database.
Here is my code
I used enum value for checkbox and textbox
Here is the enum code
public enum ChassisJobTypeEnum
{
LinerChange = 1,
ChainSetChange = 2
}
Here is the view design code
<div class="form-group row">
<label class="col-sm-3 col-form-label">Change Linear</label>
<div class="col-sm-3">
<input type="checkbox" class="form-group" id="ChassisJob#((int)ChassisJobTypeEnum.LinerChange)_Checked" placeholder="" />
</div>
<div class="col-sm-3">
<input type="text" class="form-group" id="ChassisJob.#((int)ChassisJobTypeEnum.LinerChange)_OtherJob" placeholder="" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Change Chain Set</label>
<div class="col-sm-3">
<input type="checkbox" class="form-group" id="ChassisJob#((int)ChassisJobTypeEnum.ChainSetChange)_Checked" placeholder="" />
</div>
<div class="col-sm-3">
<input type="text" class="form-group" id="ChassisJob.#((int)ChassisJobTypeEnum.ChainSetChange)_OtherJob" placeholder="" />
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit" class="btn btn-primary" id="submit-form">Submit</button>
</div>
</div>
Now, when submit the form at that time ajax is calling to the controller
$('form').submit(function (event) {
event.preventDefault();
var chassisJobs = [];
chassisJob = {
ChassisJobsTypeId: #((int)ChassisJobTypeEnum.LinerChange),
Checked: $("#ChassisJob#((int)ChassisJobTypeEnum.LinerChange)_Checked").prop('checked'),
OtherJob: document.getElementById("ChassisJob.#((int)ChassisJobTypeEnum.LinerChange)_OtherJob").value,
};
chassisJobs.push(chassisJob);
chassisJob = {
ChassisJobsTypeId: #((int)ChassisJobTypeEnum.ChainSetChange),
Checked: $("#ChassisJob#((int)ChassisJobTypeEnum.ChainSetChange)_Checked").prop('checked'),
OtherJob: document.getElementById("ChassisJob.#((int)ChassisJobTypeEnum.ChainSetChange)_OtherJob").value,
};
chassisJobs.push(chassisJob);
var serviceJobData = {
'Id': document.getElementById("Id").value,
'ChassisJob': chassisJobs
};
$.ajax({
type: "POST",
url: '/ServiceJob/AddUpdate',
data: serviceJobData,
dataType: "json",
success: function (data) {
if (data.success == true) {
alert("Data has been update successfully");
//RefreshTable();
location.reload(true);
// set focus on edit form
document.getElementById("service-job-list").scrollIntoView();
//reste form
var frm = document.getElementsByName('service-job-form')[0];
frm.reset();
}
else {
alert("Unable to insert data")
}
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to add Detail.');
}
});
});
Here is the controller in which the addupdate method is calling at submit button.
[HttpPost]
public IActionResult AddUpdate(ServiceJobModel model)
{
ServiceJob serviceJob = new ServiceJob();
bool iSInsertData = true;
var chassisJobs = _Db.ChassisJob.Where(x => x.ServiceJobId == model.Id).ToList();
if (chassisJobs.Any())
{
_Db.ChassisJob.RemoveRange(chassisJobs);
_Db.SaveChanges();
}
return Json(new { success = true });
}
Now, this is code which I tried.
For more clear, let see task image.
When I check the checkbox and enter the value in textbox at that time insert data properly and at the fetch time it shows the checkbox and textbox value properly.
now, when I uncheck the checkbox and enter the value in textbox at that time data is not inserted and at the fetch time it does not show any thing.
If you any issue to understand the question then feel free to ask.

How can I do event on text box in Angular?

I have a text box that show when I click on checkbox and I need to make an event on it that can make me bind it to object from DB
HTML:
<div ng-repeat="feture in featureEnumArray">
<input id="txtchkFet" type="checkbox" ng-model="feture.IsChecked" />
{{feture.DisplayText}}
<div ng-show="feture.IsChecked" >
<input class="form-control" type="text" ng-model="feture.Value" ng-change="getFeatureID(feture)" id="txtValue" placeholder="Type Feature Value" />
</div>
<div class="label label-danger" ng-show="feture.IsChecked && !feture.Value">
Type Value
</div>
</div>
And in Angular controller I did Like this :
$scope.getFeatureID = function (feture) {
if (feture.IsChecked) {
$scope.Planfeature = angular.copy(feture);
$scope.PlanFeatureTemp.FeatureID = $scope.Planfeature.ID;
$scope.PlanFeatureTemp.Value = $scope.Planfeature.Value;
$scope.Planfeature = [];
}
else {
var index = $scope.JAdminPlan.PlanFeatureValues.indexOf(feture);
$scope.JAdminPlan.PlanFeatureValues.splice(index, 1);
}
if (!$scope.$$phase) $scope.$apply();
};

Angularjs autocomplete directive in 2 places in same dom

Hi,
I am building an autocomplete directive and I need it at two places in the same form. The autocomplete feature works fine but it shows the same directive at both the places. I have attached a image with this question, referring the Image even if I type in teh to colum the country autocomplete is also activated, how to I bind it to only the element where user is interacting ?
following is my code for the directive
angular.module('xyz').directive('autoComplete',['$rootScope',function($rootScope){
return {
restrict:'AE',
transclude: true,
replace: true,
scope:{
selectedTags:'=model',
userdata:'=',
name:'#'
},
templateUrl: function(elem,attr){ return 'views/rad/layout/autocomplete.html' },
link:function(scope,elem,attrs){
scope.suggestions=[];
scope.selectedTags=[];
scope.selectedIndex=-1; //currently selected suggestion index
scope.search=function(){
var newSuggestions = [];
// if(attrs.userdata.indexOf(scope.searchText)===-1){
// //dataUser.unshift(scope.searchText);
// }
for(var i=0; i < scope.userdata.length;i++)
{
if(dataUser[i].toLowerCase().indexOf(scope.searchText.toLowerCase()) !== -1){
newSuggestions.push(dataUser[i]);
}
}
scope.suggestions = newSuggestions;
scope.selectedIndex = -1;
}
scope.checkKeyDown=function(event){
console.log(event.keyCode);
if(event.keyCode===40){//down key, increment selectedIndex
event.preventDefault();
if(scope.selectedIndex+1 !== scope.suggestions.length){
scope.selectedIndex++;
}
}
else if(event.keyCode===38){ //up key, decrement selectedIndex
event.preventDefault();
if(scope.selectedIndex-1 !== -1){
scope.selectedIndex--;
}
}
else if(event.keyCode===13){ //enter pressed
scope.addToSelectedTags(scope.selectedIndex);
}
}
scope.addToSelectedTags=function(index){
if(scope.selectedTags.indexOf(scope.suggestions[index])===-1){
scope.selectedTags.push(scope.suggestions[index]);
scope.searchText='';
scope.suggestions=[];
}
}
scope.$watch('selectedIndex',function(val){
if(val!==-1) {
scope.searchText = scope.suggestions[scope.selectedIndex];
}
});
scope.removeTag=function(index){
scope.selectedTags.splice(index,1);
}
}
}
}])
following is the auto complete template
<div class="tags-wrapper">
<div id="tagsList" class="tags-cloud">
<div class="suggestionListing">
<div ng-repeat="selectedTag in selectedTags track by $index" class="tag">
<span class="tagName">{{selectedTag}}</span>
<span> <b ng-click="removeTag($index)" class="fa fa-times cross"></b></span>
</div>
</div>
<div class="input-group">
<input type="text" name="{{inputname}}"placeholder="" aria-describedby="basic-addon2" id="searchInput" class="form-control no-border" ng-model="searchText" ng-keydown="checkKeyDown($event)" class="form-control" ng-model="searchText" ng-change="search()"/>
<div class="suggestions-list">
<div ng-repeat="suggestion in suggestions track by $index" class="blockSpan" ng-click="addToSelectedTags($index)" ng-mouseover="$parent.selectedIndex=$index" ng-class="{active : selectedIndex===$index}">
<div class="userAvatar">
<i class="fa fa-user"></i>
</div>
<div class="userInfo">
{{suggestion}}
</div>
<br clear="all" />
</div>
</div>
</div>
</div>

Unexpected ng-change Behavior

Looking at an exercise from AngularJS in Action, I'm trying to implement the ng-change behavior to update the select's drop-down value upon a change to the story.status.
JS
$scope.setCurrentStatus = function(status) {
if(typeof $scope.currentStory !== 'undefined') {
$scope.currentStory.status = status.name;
}
};
$scope.setCurrentStory = function(story) {
$scope.currentStory = story
$scope.currentStatus = $scope.statusesIndex[story.status];
$scope.currentType = $scope.typesIndex[story.type];
console.log("$scope.currentType", $scope.currentType);
};
Note that, when I select a story, the logging from setCurrentStory executes, but not setCurrentStatus.
HTML
<div class="control-group">
<label class="control-label" for="inputType">Type</label>
<div class="controls">
<select id="inputType"
ng-model="currentType"
ng-options="t.name for t in types"
ng-change="setCurrentType(currentType)"></select>
</div>
</div>
</form>
Fiddle - http://jsfiddle.net/qLue3/1/

Resources