I have a list of radio button values in ControllerA, printed in the view with ng-repeat. The list comes from a service. Now I want to check which radio button is selected in ControllerB.
How do I get the current selected value?
Do I need to add a $watch function in ControllerA and update the service that way?
Or is there a different way of basically binding a variable from a controller to variable in a service?
There's no need to set a $watch; it's all about sharing state between controllers.
Javascript
var app = angular.module('app', []);
app.factory('myState', function() {
// For this example I'm just returning the state directly, but it can also
// be returned from some function or even some backend api. Just remember
// that factories (services/providers) are singletons and will point always
// to the same instance within your app.
return {
chickenEgg: 'egg'
};
});
app.controller('ControllerA', function($scope, myState) {
$scope.formData = myState;
});
app.controller('ControllerB', function($scope, myState) {
$scope.result = myState;
});
Html
<div ng-controller="ControllerA">
<h2>ControllerA</h2>
<form class="form">
<label>Chicken or the Egg?</label>
<div class="form-group">
<div class="radio">
<label>
<input type="radio" name="chickenEgg" value="chicken" ng-model="formData.chickenEgg">Chicken
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="chickenEgg" value="egg" ng-model="formData.chickenEgg">Egg
</label>
</div>
</div>
</form>
</div>
<div ng-controller="ControllerB">
<h2>ControllerB</h2>
<pre><code>result = {{ result | json }}</code></pre>
</div>
You can see it in action in this plunker.
Related
I am new to Angularjs.I have a datepicker in ionic.After selecting date input is getting value of the selected date.Now i am trying to acces this value in Controller by using $scope but i am unable to access.
Here is my html
<div class="list">
<label class="item item-input">
<input type="text" data-ng-model="dateValue" disabled>
</label>
</div>
<my-calendar display="dateValue" dateformat="'yyyy-MM-dd'"></my-calendar>
<button id="fieldWork-button21" data-ng- click="saveFieldWork(fieldWork)"></button>
I am calling save function after submit.I am binding other values with fieldWork object.
Here is the Controller.js
$scope.dateValue = "";
$scope.saveFieldWork = function(fieldWork) {
fieldWork.fieldDate = $scope.dateValue;
//other code
};
Here I am not able to get selected Date value. But in the input after selecting date it is displaying correct date.
At present it is displaying empty string instead of selected date. Can anyone tell how to get this value into Controller? If AngularJs supports two way data binding then why am I not able to get ng-model value from html to Controller?
You don't have access to fieldWork variable in html, So you can not use it in data-ng-click.
<button id="fieldWork-button21" data-ng-click="saveFieldWork()"></button>
Look this
(function() {
'use strict';
angular.module('player', [])
.controller('MainCtrl', ['$scope', function($scope) {
var fieldWork = {};
$scope.saveFieldWork = function() {
fieldWork["fieldDate"] = $scope.dateValue;
console.log(fieldWork);
//other code
};
}])
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js"></script>
<div ng-app='player'>
<div ng-controller='MainCtrl'>
<div class="list">
<label class="item item-input">
<input type="text" data-ng-model="dateValue">
</label>
</div>
<button id="fieldWork-button21" data-ng-click="saveFieldWork()">Save</button>
</div>
</div>
//This is my HTML code wherein am returning a list from backend.
<ul>
<li ng-repeat=" opt in bcfList1 track by $index" > <input type="radio" name="buildid" id="buildid" ng-model = $parent.selected ng-value="bcfList1" required>
{{ opt }}
</li>
</ul>
//This is my controller.js program
$scope.getDetails =function(data){
var id=data.id;
$('#addNode3').modal('show');
UpgradeService.getDataById(id).then(function(data){
if(data!=null){
$scope.List1=data.BUILDNUMBER;
}
});
}
I need to get the string value that'll be listed in front of the radio button. So once I click on radio button it should send that value to the controller.js
By using ng-model I need a solution.
Help me out!!
You need to add ng-change to your input fields with a call to that function. Here is a quick demo:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.b = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$scope.getDetails = function(index) {
console.log("sending data", index,$scope.selected);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="a in b track by $index">
<input type="radio" ng-model="$parent.selected" ng-value="a" ng-change="getDetails($index)" /> {{a}}
</div>
</div>
If I understand correctly, you need to gather which input type radio was clicked in controller and send this information to backend.
ng-model directive is very good approach here and you can use it just like so:
html
<label>
One
<input type="radio" value="one" ng-model="radio">
</label>
<label>
Two
<input type="radio" value="two" ng-model="radio">
</label>
<br><br>{{ radio }}<br>
JS
app.controller('MainCtrl', function($scope) {
$scope.radio = '';
$scope.consoleLogRadio = function() {
console.log($scope.radio);
}
});
Take a look at plunker example
hope you guys are kicking and jumping. Thanks for your usual understanding.
Frameworks: AngularJS, NodeJS
I am designing a login page. But the data to be compared with is an array of items in testData.html. I want to call the data on the login.html and compare it with user's input.
The login form works properly but the data is not read. I tried compiling the dataobject.html file separately, and it did not run.
I do not want to store this data in a .json file.
Later I will learn how to use the MongoDB to read data and compare
Please check the codes below.
[LOGIN.HTML]
<div ng-app="myApp" ng-controller="loginCtrls" style="height:auto;">
<form name="lForm">
<div class="container">
<label><b>Username</b></label>
<input class="w3-round" type="text" name="username" placeholder="Username" ng-model="username" required>
<div align="right" style="width:550px;">
<span style="color:red" ng-show="lForm.username.$dirty && lForm.username.$invalid">
<span ng-show = "lForm.username.$error.required">Username is required.</span>
</span>
</div>
<label><b>Password</b></label>
<input class="w3-round" type="password" name="password" ng-model="password" placeholder="Password" required>
<div align="right" style="width:550px;">
<span style="color:red" ng-show="lForm.password.$dirty && lForm.password.$invalid">
<span ng-show = "lForm.password.$error.required">Password is required.</span>
</span>
</div>
<div align="center">
<button class="w3-btn w3-teal w3-round" style="height:45px; width:100%; font-size:16px;" ng-disabled = "lForm.username.$dirty && lForm.username.$invalid || lForm.password.$dirty && lForm.password.$invalid" ng-click="chkData()">Click to Login</button>
</div>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#f1f1f1; margin-top:0;">
<span>Forgot password?</span>
</div>
</form>
<h4>{{result}} login attempt</h4>
</div>
<script src="js/loginCtrl.js"></script>
[LOGINCTRL.JS]
// JavaScript Document
var app = angular.module('myApp', []);
app.controller('loginCtrls', function($scope, $http) {
//get the file from the dataobject.html file
$http.get("dataobject.html").then(function (response) {
//parse the array object to $scope.users
$scope.users = response.data.records;
});
//this function checks the user's input and
//compares it with the any match in object array
//the object array data has been passed into $scope.users
$scope.chkData = function(){
$scope.users = $scope.data.records;
angular.forEach($scope.users, function(value, key){
if(angular.equals(value.Username, $scope.username) && (value.Password, $scope.password)){
$scope.result = "Successful ";//msg to be displayed
}else {
$scope.result = "Unsuccessful ";//msg to be displayed
}
});
}
});
[DATA OBJECT.HTML]
<script src = "js/angular.min.js" type="text/javascript"></script>
<div ng-app="myApp" ng-controller="mdata">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('mdata', function($scope) {
$scope.data =
{ "records":[ {"Username":"Alfreds","Password":"alfred","Session ID":"1"}, {"Username":"Ana","Password":"ana","Session ID":"2"}, {"Username":"Moreno","Password":"moreno","Session ID":"3"}] };
});
});
</script>
I would recommend to do it using a service. Angular services are singletons. So, from one controller, you put the data in a service, switch pages, get the data from the service.
NOTE: if user refreshes the page, the data in the service will be lost, as services (or angular for that matter) does not persist state.
ofc, everyone will have their own solution. I see you are a beginner, so the answer is meant to help you get a grasp of angular.
You can store your data either on the $rootScope or by creating localStorage Services and u can access data anywhere in application but the best practices are creating some localStorage services.
I am unable to get the value of a selected radio button in angular controller. The reportTypeId I use in angular controller does not fetch the value of the radio button. Can someone guide me where exactly I am wrong ?
HTML
<div class="col-md-3">
<input type="radio" ng-model="reportTypeRadio" value="reportType.reportTypeId">
<a href="#reportTypeEntityList/{{reportType.reportTypeId}}">
{{reportType.reportTypeLabel}}
</a>
</div>
Controller
mdmApp.controller('Controller', function($scope, $http, $location, $routeParams) {
$scope.reportTypeRadio = reportTypeId;
$scope.viewReportTypeEntityList = function() {
$location.path('/reportTypeEntityList/' +reportTypeId);
}
});
You need to use model value from ngModel directive:
$scope.viewReportTypeEntityList = function() {
$location.path('/reportTypeEntityList/' + $scope.reportTypeRadio);
};
It worked. I just made the below changes to my html. used ng-value instead of value, and $parent in ng-model to use the parent scope of the ng-repeat directive.
<div class="col-md-3">
<input type="radio" ng-model="$parent.reportTypeRadio" ng-value="reportType.reportTypeId">
<a href="#reportTypeEntityList/{{reportType.reportTypeId}}">
{{reportType.reportTypeLabel}}
</a>
I have a form with checkboxes and other input fields.
The data-ns-form directive is used for submitting form data via ajax. The controller for this form is UserController.
HTML
<div ng-controller="UserController">
<form data-ns-form="formData">
Full Name : <input type="text" name="fullname" ng-model="formData.fullname" />
Favourite Beverage :
<label>
<input type="checkbox" name="beverages[]" ng-model="formData.beverages[0]" value="coffee"> Coffee
</label>
<label>
<input type="checkbox" name="beverages[]" ng-model="formData.beverages[1]" value="tea"> Tea
</label>
<label>
<input type="checkbox" name="beverages[]" ng-model="formData.beverages[2]" value="colddrinks"> Cold Drinks
</label>
<button type="submit"> Send </button>
</form>
</div>
Controller
app.controller('UserController', function($scope){
$scope.formData = {fullname : '', beverages : []};
});
Directive
app.directive('nsForm', function(){
return {
restrict : "A",
scope: {
formData : "=nsForm"
},
link : function(scope, iElem, iAttr) {
$(iElem).on('submit', function(e) {
e.preventDefault();
console.log("FORM DATA");
console.log(scope.formData);
});
}
}
});
A little description
When I submit the form I get boolean TRUE for checked checkboxes, but instead I want the value inside the value attirbute. For instance, If I checked 'coffee' and 'Cold Drinks', I get beverages=[true,false,true], but what do I want is beverages['coffee','colddrink'].
What is the AngularJS way of doing it?
And Also.
Is there any preferred way of submitting form in AngularJS instead of creating directives myself ?
I don't see any reason for the "name" attribute here. You need to use ng-click with a function to save your data - and that should be taken care of by a service. There's a lot you can do with angular...search the docs for anything you're doing (see checkboxes in the docs, for example).
Live demo here (click).
<div ng-controller="UserController">
Favourite Beverage :
<label>
<input type="checkbox" ng-model="formData.beverages[0]" ng-true-value="coffee">Coffee
</label>
<label>
<input type="checkbox" ng-model="formData.beverages[1]" ng-true-value="tea">Tea
</label>
<label>
<input type="checkbox" ng-model="formData.beverages[2]" ng-true-value="colddrinks">Cold Drinks
</label>
<button ng-click="save()"> Send </button>
</div>
js:
var app = angular.module('myApp', []);
app.factory('myService', function($http) {
var myService = {
save: function(data) {
//your ajax call here
console.log(data);
}
};
return myService;
});
app.controller('UserController', function($scope, myService) {
$scope.formData = {};
$scope.formData.beverages = [];
$scope.save = function() {
myService.save($scope.formData);
};
});
Also, you should probably have all of your data (the drink values, for example) in your javascript rather than the html, then bind it to the page. Or in the database, then into js, then onto the page. That all depends on how dynamic your information needs to be - just be sure to think ahead.