Unable to get value from html to controller - javascript

Here I am sending data of mail id and its visibility to server for two different users for one I have included mail and its visibility and for another hiding visibility.
To hide visibility I am using <div ng-if="atom.type === 'person'">.
Hiding and showing is working properly but problem is that on both case
it is showing visibility undefined.
If I am not using <div ng-if="atom.type === 'person'">. then it is properly sending visibility.
How to resolve this?
My Code is bolow
var myApp = angular.module('myApp', ['ngMessages']);
myApp.controller('profileInfo', function($scope, $http) {
$scope.authorized = false;
$scope.visibility = ["Private", "Friends", "Public"];
$scope.id = 0;
$atom.type = 'person';
$scope.addMailId = function(data) {
console.log(data);
$scope.mailidDetaillD = {
'mailidDetaillList[0].email': data.mailid,
'mailidDetaillList[0].visibility': data.visibility,
'pageId': $scope.id,
};
console.log($scope.mailidDetaillD);
}
});
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular-messages.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<dd class="col-sm-7 col-md-7 col-lg-7">
<div class="pull-right" ng-if="authorized">
<a ng-click="showAddMailIdDiv()" ng-model="addMailIdLink">add MailId Details</a>
<div class="add-school" ng-show="showAddMailId">
<form action="AddMailId" id="AddMailId" name="addmail" cssClass="form-horizontal">
<div class="form-group">
<div class="col-lg-2">
<label>Mail Id</label>
</div>
<div class="col-lg-6">
<input type="text" ng-model="mail.mailid" name="mailid" placeholder="Enter mail id" required class="form-control" />
<div ng-messages="addmail.mailid.$error" ng-if="addmail.mailid.$touched">
<p class="field-err" ng-message="required">MailId Required</p>
</div>
</div>
</div>
<div ng-if="atom.type === 'person'">
<div class="form-group">
<div class="col-lg-2">
<label>Visibility</label>
</div>
<div class="col-lg-6">
<select ng-model="mail.visibility"
ng-init=" mail.visibility = visibility[1]"
ng-options="x for x in visibility"
class="form-control"
name="mailvisibility" required>
</select>
<div ng-messages="addmail.mailvisibility.$error" ng-if="addmail.mailvisibility.$touched">
<p class="field-err" ng-message="required">Select Mail visibility</p>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-2">
<label class="sr-only">Submit</label>
</div>
<div class="col-lg-6 pull-right">
<input type="button" value="add" ng-click="addMailId(mail)" ng-disabled="addmail.$invalid" cssClass="btn btn-sm btn-primary" />
<input type="button" ng-click="hideAddMailIdDiv()" value="cancle" class="btn btn-sm btn-secondary" />
</div>
</div>
</form>
</div>
</div>
</dd>
last console.log is showing following result
mailidDetaillList[0].email: "W#w.com"
mailidDetaillList[0].visibility: undefined
pageId: 2337
after removing <div ng-if="atom.type === 'person'">
mailidDetaillList[0].email: "ss#s.com"
mailidDetaillList[0].visibility: "Public"
pageId: 2337

Delete the ng-init:
<select ng-model="mail.visibility"
̶n̶g̶-̶i̶n̶i̶t̶=̶"̶ ̶m̶a̶i̶l̶.̶v̶i̶s̶i̶b̶i̶l̶i̶t̶y̶ ̶=̶ ̶v̶i̶s̶i̶b̶i̶l̶i̶t̶y̶[̶1̶]̶"̶
ng-options="x for x in visibility"
class="form-control"
name="mailvisibility" required>
</select>
And set visibility from the controller:
$scope.mail = { visibility: $scope.visibility[1] };
AngularJS is an MVC - Model-View-Controller framework. The framework renders the View from the Model. The Controller creates the Model. Using ng-init to create the Model is going the wrong way. It makes an App that is difficult to understand, test, debug, and maintain.
The ng-init directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit. See AngularJS ng-init Directive API Reference.

Related

Binding two HTML tags together

.controller('mainCtrl', ['$scope', '$http', function($scope, $http){
$scope.wales_total = function(){
$select_7 = parseInt($(".select_7 strong").html().replace(',' , ''));
console.log($select_7);
$welsh_total = Number($select_7 ||0);
return $welsh_total;
};
$scope.scotland_total = function(){
$select_8 = parseInt($(".select_8 strong").html().replace(',' , ''));
$total = Number($select_8 ||0);
return $total;
};
$scope.ireland_total = function(){
$select_9 = parseInt($(".select_9 strong").html().replace(',' , ''));
$total = Number($select_9 ||0);
return $total;
};
$scope.totals_test = $(".total").html();
HTML:
<div ng-switch-when="NHS Wales Health Board">
<div class="col-sm-6 col-sm-offset-3">
<form>
<label class="pull-left">Health Board</label>
<select ui-select2 class="form-control select_2nd" ng-model="selectedOption_7" ng-options="data as data.displayName for data in wales_data"></select>
<div class="population_estimate_wrapper">
<p class="population_estimate">Population Estimate</p>
<div class="population_estimate_box" ng-model="selectedOption_7">
<p class="hidden select_7"><strong>{{selectedOption_7.value}}</strong></p>
<p class="total" ng-model="total">{{wales_total()}}</p>
</div>
</div>
</form>
</div>
</div>
<div ng-switch-when="NHS Scotland Health Board">
<div class="col-sm-6 col-sm-offset-3">
<form>
<div class="form-group">
<label class="pull-left">Health Board</label>
<select ui-se-lect2 class="form-control select_2nd" ng-model="selectedOption_8" ng-options="data as data.displayName for data in scotland_data"></select>
<div class="population_estimate_wrapper">
<p class="population_estimate">Population Estimate</p>
<div class="population_estimate_box" ng-model="selectedOption_8">
<p class="hidden select_8"><strong>{{selectedOption_8.value}}</strong></p>
<p class="total">{{scotland_total()}}</p>
</div>
</div>
</div>
</form>
</div>
</div>
<div ng-switch-when="Northern Ireland Health And Social Services Board">
<div class="col-sm-6 col-sm-offset-3">
<form>
<div class="form-group">
<label class="pull-left">Health Board</label>
<select ui-select2 class="form-control select_2nd" ng-model="selectedOption_9" ng-options="data as data.displayName for data in ireland_data">
<option selected value>Select</option>
</select>
<div class="population_estimate_wrapper">
<p class="population_estimate">Population Estimate</p>
<div class="population_estimate_box" ng-model="selectedOption_9">
<p class="hidden select_9"><strong>{{selectedOption_9.value}}</strong></p>
<p class="total">{{ireland_total()}}</p>
</div>
</div>
</div>
</form>
</div>
</div>
Then we have a hide show function, that will hide the above section, and show code that is currently hidden.
HTML2:
<div class="main_container_wrapper">
<div class="main_container">
<div class="budget_row odd bg_lines_1">
<p class="blue size15"><strong>Primary non-familial hypercholesterolaemia or mixed dyslipidaemia</strong></p>
<div class="row_left">
<p class="grey size13"><strong>Total catchment population</strong></p>
</div>
<div class="row_right text-center">
<p class="number_box">{{totals_test}}</p>
</div>
</div>
So basically, whatever html is in the class="total" should be dumped into a $scope.totals_test variable. What I want to do, is if i go back to the previos page, and change the html, have angular update that when i go forward again. (its all on one page, just showing and hiding different sections)
I can't understand fully what you're asking, but I believe you're looking for the following View and Controller.
HTML
<div ng-if="!showParagraph">
<p>{{number()}}</p>
<button ng-click="show">Click Me</button
</div>
<div class="example_2" ng-if="showParagraph">
<p ng-bind="number()"></p>
</div>
CONTROLLER
$scope.show= function() {
$scope.showParagraph = true;
};
$scope.number = function() {
5 * 5
};
you can use ng-show for show hide instead of calling jquery, jquery is not under digest of AngularJS
also use something like this: $scope.number.show... if you use hirerichy like this, it will reflect in controller.. i dont know why, but it works

use ng-controller in script tag with text/ng-template

I'm trying to use ng-controller in script tag witch is a template and has ng-template directive
i don't know why it's now working
<script type="text/ng-template" id="modal-5" >
<div ng-controller="reserveModalCtrl">
<div class="modal-header">
<button type="button" class="close" ng-click="currentModal.close();"
aria-hidden="true">×</button>
<h4 class="modal-title">Rserve Shortcode</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="field-1" class="control-label">Shortcode</label>
<input type="text" class="form-control" id="field-1"
value="30570" disabled>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="field-2" class="control-label">Company</label>
<div id="field-2">
<select class="form-control"
ng-model="currentShortCode.companyId">
<option ng-repeat="company in companies track by $index"
value="{{company._id}}"> {{company.companyName
+ ' (' + company.companyLatinName + ')'}}</option>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label">Until</label>
<div>
<div class="date-and-time">
<input type="text" ng-model="currentShortCode.date"
class="form-control datepicker"
data-format="D, dd MM yyyy">
<input type="text" ng-model="currentShortCode.time"
class="form-control timepicker" data-template="dropdown"
data-show-seconds="true" data-default-time="11:25 AM"
data-show-meridian="true" data-minute-step="5"
data-second-step="5" />
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white"
ng-click="currentModal.close();">Close</button>
<button type="button" class="btn btn-info"
ng-click="currentModal.dismiss();">Reserve</button>
</div>
</div>
and my controller
app.controller('reserveModalCtrl', function ($scope, ShortCodeService) {
$scope.companies = ShortCodeService.companies;
$scope.shortCodes = ShortCodeService.shortCodes;
$scope.test = 'test';
});
when i use this on div element it's working but in this case not.
The documentation for the script directive says that you can use it to:
Load the content of a element into $templateCache, so that the template can be used by ngInclude, ngView, or directives. The type of the element must be specified as text/ng-template, and a cache name for the template must be assigned through the element's id, which can then be used as a directive's templateUrl.
So to actually render the template, you must either map it to a route when configuring the router (either standard ngRoute or ui-router) or include it with ngInclude (for example, <div ng-include="modal-5"></div>) or as the templateUrl attribute of a directive definition object.

Angular make input valid manually

I am using a bootstrap datepicker. when i click on the icon date& time automatically enters into the input. but the input remained as invalid since i did not interacted with it directly. has any one faced this problem.
here is the plnkr for that: http://plnkr.co/edit/yBmwZCCPvTOQWE6q3BW5
view
<body data-ng-controller="ReservationController as resvnCtrl">
<div class="container">
<div class="col-lg-6 col-lg-offset-3 col-md-8 col-md-offset-2 col-sm-12 col-xs-12 ">
<div>
<h2 class="text-center page-heading">Make a reservation</h2>
</div>
<div>
<form role="form" name="resvnCtrl.form" data-ng-submit="resvnCtrl.submitForm(resvnCtrl.form.$valid)" novalidate>
<div class="form-group" data-ng-class="{'has-error':resvnCtrl.form.time.$invalid && (resvnCtrl.form.time.$dirty || resvnCtrl.form.$submitted) }">
<label class="control-label">Date-Time</label>
<div class='input-group date' id='datetimepicker'>
<input type="text" name="time" id="time" data-ng-model="resvnCtrl.reservation.time"
placeholder="Enter Desired Time" class="form-control" required>
<span class="input-group-addon pointer" data-date-picker>
<i class="fa fa-calendar"></i>
</span>
</div>
<div data-ng-messages="resvnCtrl.form.time.$error" data-ng-if="resvnCtrl.form.time.$dirty || resvnCtrl.form.$submitted">
<p class="help-block" data-ng-message="required">Date and Time required</p>
</div>
</div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<input type="submit" name="submit" id="submit" value="Make Reservation" class="btn btn-primary btn-block " >
</div>
</div>
</form>
</div>
</div>
</div>
</body>
controller
var app = angular.module('plunker', []);
angular.module('plunker')
.controller('ReservationController',ReservationController);
ReservationController.$inject=['$scope'];
function ReservationController($scope) {
var resvnCtrl=this;
resvnCtrl.reservation={};
resvnCtrl.confirmation={};
$('#datetimepicker').datetimepicker();
resvnCtrl.submitForm=function(isValid){
alert("valid:"+resvnCtrl.form.time.$valid);
}
}
I think you can refer to angular-strap:http://mgcrea.github.io/angular-strap/#/datepickers. when you import angular-strap.min.js, angular-strap.tpl.min.js and libs.min.css to your index.html. your app.js should be like this:
var app = angular.module('plunker', ['mgcrea.ngStrap.datepicker']);
That's the curse of usage jQuery within angular. Your models controller updates only $viewValue when plugin initialized and that does not trigger digest. Digest triggered my another action - focus in or out that is run digest.
Solution for this is watcher that will manually set $modelValue by $setViewValue() method so angular will know something happened and update validation.
And please, create separate directive for datepicker that will initialize it on element you used directive on.

Keydown event not updating the $scope variable for dropdown in angularjs

I have a simple page with 2 fields. I enter the goal name and the use tab to navigate to the next field and then hit the down arrow key to select the Public Group value and when I click the save button, the value of the picklist is setting to Individual which is incorrect. I am not exactly sure how to make the $scope variable pick the updated value from the dropdown
Here's the fiddle
<div ng-app>
<div class="container" ng-controller="goalCtrl">
<div class="row">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">New Record</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-4">
<div class="form-group">
<label for="goalName" class="control-label">Name</label>
<input type="text" class="form-control" id="goalName" placeholder="Goal Name" ng-model="goalie__goal__c.Name">
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label for="fulfilment" class="control-label">Fulfilment</label>
<select class="form-control" id="fulfilment" ng-model="goalie__goal__c.goalie__Fulfilment__c">
<option selected>Individual</option>
<option>Public Group</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<center>
<button class="btn btn-success" ng-click="save()"> Save and add critera</button>
<button class="btn btn-danger" ng-click="cancel()">Cancel</button>
</center>
</div>
</div>
</div>
</div>
</div>
</div></div>
Controller
function goalCtrl($scope) {
$scope.save = function() {
alert(JSON.stringify($scope.goalie__goal__c));
}
}
Update
I updated the controller where I am setting the value to Individual explicitly and then when I hit the save button all the values are updated correctly in the $scope. Not sure why its not working it the initial case.
function goalCtrl($scope) {
$scope.goalie__goal__c = {};
$scope.goalie__goal__c.goalie__Fulfilment__c = 'Individual';
$scope.save = function() {
alert(JSON.stringify($scope.goalie__goal__c));
}
}

scope function inside controller not updating the values according to ng-models in the view

Hi i got this function in the controller that is called from the ng-view:
productApp.controller('ModalInstanceCtrl', function ($scope, $modalInstance, productFactory, prodId) {
$scope.ok = function () {
console.log($scope.model_productDescription);
$scope.$watch(['model_productBrand,model_productName,model_productDescription,model_productPrice, model_productStock'], function() {
var stock = '';
if($scope.model_productStock) {
stock = 'AVAILABLE';
}else{
stock = 'NO STOCK';
}
var productObject = {
id : prodId,
prodBrand : $scope.model_productBrand,
prodName : $scope.model_productName,
description : $scope.model_productDescription,
price : $scope.model_productPrice,
prodStock : stock
}
productFactory.updateProductById(productObject, function successCallback(data) {
// do something here in data
}, function errorCallback(data, status) {
alert(data + ' Failed with error ' + status);
});
})
};
});
This is the modal.htm body:
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" ng-click="cancel()">×</button>
<h4 class="modal-title">Modify a Product</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<fieldset>
<!-- Row 1 -->
<div class="col-md-12 col-centered">
<div class="control-group">
<label class="control-label" for="prod_brand">Product Brand</label>
<input type="text" id="prod_brand" class="form-control"
ng-model="model_productBrand" required="required" value="prod.prodBrand">
</div>
<div class="control-group">
<label class="control-label" for="prod_name">Product Type</label> <input
type="text" id="prod_name" class="form-control"
ng-model="model_productName" required="required" value="prod.prodName">
</div>
<div class="control-group">
<label class="control-label" for="prod_price">Price</label>
<div class="input-group">
<span class="input-group-addon">$</span> <input type="text"
class="form-control" ng-model="model_productPrice" value="prod.price"> <span
class="input-group-addon">.00</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="prod_description">Description</label>
<textarea id="prod_description" class="form-control" ng-model="model_productDescription" cols="70" rows="3">{{prod.description}}</textarea>
</div>
<div class="control-group" style="margin-top: 10px">
<div class="input-group">
<span class="input-group-addon"> <input type="checkbox" ng-model="model_productStock">
</span>
<span class="form-control no-cursor">Stock</span>
</div>
</div>
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="cancel()">Close</button>
<button type="button" class="btn btn-primary" ng-click="ok()">Edit product</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
Now, if i type in the textarea (for example), and press the ok button, it will get into this function. Now, since the textarea value has changed, shouldn't be reflected in the $scope.productDescription value? looks like it's not. I thought that whenever you make a change in the model, it would override the $scope.model_name value, should i use ng-change or any other directive for this?
Tried adding a $watch but it's not working either, any suggestion?
P.S: console.log($scope.model_productDescription); // shows the old description despite the fact i change it
Thanks.
The most probable cause of this is that your model.html is creating child scope. The changes that you do to the model property are local to child and cannot be seen in the parent due to prototypal inheritance.
What you can try is to create an object on the controller and do binding on object property.
$scope.productObject={};
Do the textarea binding to
<textarea id="prod_description" class="form-control" ng-model="productObject.productDescription" cols="70" rows="3">{{prod.description}}</textarea>
Now the changes would be reflected in productObject.productDescription property.
Also go through this wiki to understand how does scope inheritance works https://github.com/angular/angular.js/wiki/Understanding-Scopes
God... i'm going to fix it as of now by doing this:
From the view:
<button type="button" class="btn btn-primary" ng-click="ok(model_productBrand, model_productName, model_productPrice, model_productDescription, model_productStock)">Edit product</button>
From the controller passing the vars to the ok() function:
$scope.ok = function (model_productBrand, model_productName, model_productDescription, model_productPrice, model_productStock) {
Yeah... i know it looks UGLY as hell, but bleh...
Thank you, anyway i'm going to tick your answer as correct since the solution you gave me is really convenient, the only problem was that my project was kinda bad design for the solution you provided :P but is good!

Categories

Resources