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
}
}]);
Related
The ng-model directive seems to be lacking a reference to the actual object within the JavaScript, but only for string values. Using the list of dictionary objects and looping over the elements with ng-repeat as shown below though, it works.
I can only think that it may be due to returning the array acts like returning a reference to the object, whereas returning the string variable is simply returning the literal string, neutralizing the Angular's ability to do it's two-way data binding and leaving me with a variable that still holds a value of undefined.
Why is my service module below unable to pull the updated value from the view for the variable gitRelease?
In a service module I have this functionality:
(function () { //start iife
'use strict';
angular.module('gms.autoDeploy')
.factory('AutoDeployService', ["$http", "$q", "$log", "$cookies", "APP_CONFIGS", "SweetAlert", "$timeout", "GridSettingsService", "APP_USER", AutoDeployService]);
function AutoDeployService($http, $q, $log, $cookies, APP_CONFIGS, $timeout, SweetAlert, GridSettingsService, APP_USER) {
var tibcoCopyJobs = [];
var gitRelease = "";
function addNewTibcoCopyJob() {
tibcoCopyJobs.push({
sourceServer: "",
sourcePath: "",
destinationServer: "",
destinationPath: ""
});
}
function getTibcoCopyJobs() { return tibcoCopyJobs; }
function getGitRelease(){ return gitRelease; }
function extractFormData() {
console.log(gitRelease);
for (var i = 0; i < tibcoCopyJobs.length; i++) {
console.log(tibcoCopyJobs[i]);
}
}
return {
addNewTibcoCopyJob: addNewTibcoCopyJob,
getTibcoCopyJobs: getTibcoCopyJobs,
getGitRelease: getGitRelease,
extractFormData: extractFormData
};
} //end AutoDeployService
}()); //end iife
Using it with this controller:
angular.module("gms.autoDeploy").controller('AutoDeployController', ['$scope', '$compile', 'AutoDeployService',
function ($scope, $compile, AutoDeployService) {
var model = this;
init();
function init() {
model.tibcoCopyJobs = AutoDeployService.getTibcoCopyJobs();
model.gitRelease = AutoDeployService.getGitRelease();
}
function btn_addNewTibcoCopy() { AutoDeployService.addNewTibcoCopyJob(); }
function btn_extractFormData() { AutoDeployService.extractFormData(); }
model.btn_addNewTibcoCopy = btn_addNewTibcoCopy;
model.btn_extractFormData = btn_extractFormData;
}
]);
To give functionality to this view:
<div ng-controller="AutoDeployController as autoDeploy">
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<input type="text" class="form-control" ng-model="autoDeploy.gitRelease" placeholder="MM-DD-YYYY">
</div>
</div>
<div class="row">
<fieldset class="col-md-2" style="margin-bottom: 10px" ng-repeat="item in autoDeploy.tibcoCopyJobs track by $index">
<legend>Copy</legend>
<input type="text" class="form-control" placeholder="Source Server..." ng-model="item.sourceServer">
<br/>
<input type="text" class="form-control" placeholder="Source Path..." ng-model="item.sourcePath">
<br/>
<input type="text" class="form-control" placeholder="Destination Server..." ng-model="item.destinationServer">
<br/>
<input type="text" class="form-control" placeholder="Destination Path..." ng-model="item.destinationPath">
</fieldset>
</div>
<button ng-click="autoDeploy.btn_extractFormData()">extract</button>
<button ng-click="autoDeploy.btn_addNewTibcoCopy()">TIBCO copy</button>
</div>
</div>
I think you have explained why in your question. Array is returned by reference, whereas string is just copied by value. But I will try to make it a bit more clear.
When you do
model.gitRelease = AutoDeployService.getGitRelease();
the model object will create property getRelease like this:
{getRelease: "", ... (more properties from the ctrl)}
so whatever you update in the view it will just update the getRelease in the controller.
One possible fix is like what Jags mentioned in the comment.
Or you can make a reference to your service in the ctrl
var model = this;
model.autoDeployService = AutoDeployService;
In your view
<input type="text" class="form-control" ng-model="autoDeploy.autoDeployService.gitRelease" placeholder="MM-DD-YYYY">
that should work.
I am trying to save the checked items in the checkbox and display them. I can store them locally and display. However the tick is not stored. Every time i reload the page the checked item that is stored is displayed but the tick is missing. Any idea on how to also store the tick in checked items and display them in the checkbox?
jsfiddle code I am currently trying is : https://jsfiddle.net/bhgmw7ey/
the html code is
'
<div ng-repeat="chip in colores" >
<input type="checkbox" name="{{chip.codigo}}" id="{{chip.codigo}}" ng-model="chip.checked" ng-change="chipsColores()" ng-click="$storage.a = fav">
<label>{{chip.codigo}}</label>
</div>
<div ng-repeat="favorite in $storage.a">
localStorage: {{favorite.codigo}}
</div>
</div>
'
the javascript code is
(function() { angular.module('myApp',['ngStorage']) .controller('favCtrl',[ '$scope', '$filter', '$localStorage', function ( $scope, $filter, $localStorage) {
$scope.colores = [
{'nombre':'blue', 'codigo':'1111'},
{'nombre':'green', 'codigo':'2222'},
{'nombre':'red', 'codigo':'3333'} ];
$scope.chipsColores = function () {
$scope.fav = $filter('filter')($scope.colores, {checked: true});} $scope.$storage = $localStorage.$default({ });}])})();'
your ngStorage is not properly used referring to the official wiki of this library https://github.com/gsklee/ngStorage.
Following the get started guide u should implement the localstorage by bind it to a scope variable so that it can watch and update the variables in localstorage for u.
For ur case it should look like
<div ng-app="myApp">
<div ng-controller="favCtrl">
<div ng-repeat="chip in $storage.colores" >
<input type="checkbox" name="{{chip.codigo}}" id="{{chip.codigo}}" ng-model="chip.checked" ng-change="chipsColores()" >
<label>{{chip.codigo}}</label>
</div>
<div ng-repeat="favorite in $storage.colores">
localStorage: {{favorite.codigo}}
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.6/ngStorage.min.js"></script>
And JS:
angular.module('myApp',['ngStorage'])
.controller('favCtrl',[ '$scope', '$filter', '$localStorage', function ( $scope, $filter, $localStorage) {
$scope.chipsColores = function () {
$scope.fav = $filter('filter')($scope.$storage.colores, {checked: true});
}
//move the 'colores' into storage
$scope.$storage = $localStorage.$default({
colores : [
{'nombre':'blue', 'codigo':'1111'},
{'nombre':'green', 'codigo':'2222'},
{'nombre':'red', 'codigo':'3333'}
]
});
}])
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.
Im trying to bind value of radio button from ionic controller. The following is the code i have used for.
<div class="list">
<ion-radio ng-model="SearchChoice" ng-value="All" ng-click="SearchByFilter('All')"> ALL <div id="badge-all" class="count-jkt"> <span ng-bind="AllCount.OnGoing"></span></div></ion-radio>
<ion-radio ng-model="SearchChoice" ng-value="New" ng-click="SearchByFilter('New')"> NEW <div id="badge-new" class="count-jkt">{{AllCount.New}}</div></ion-radio>
</div>
and my controller is,
.controller('MainCtrl', function($scope) {
$scope.SearchChoice = "All";
$scope.SearchByFilter = function(item) {
console.log( "Filter:", item);
};
});
Here the value is not binding properly. Kindly help me guys!
Could you try it using the . notation ?
<div class="list">
<ion-radio ng-model="model.SearchChoice" ng-value="All" ng-click="SearchByFilter('All')"> ALL <div id="badge-all" class="count-jkt"> <span ng-bind="AllCount.OnGoing"></span></div></ion-radio>
<ion-radio ng-model="model.SearchChoice" ng-value="New" ng-click="SearchByFilter('New')"> NEW <div id="badge-new" class="count-jkt">{{AllCount.New}}</div></ion-radio>
</div>
.controller('MainCtrl', function($scope) {
$scope.model = {
SearchChoice: "All"
};
$scope.SearchByFilter = function(item) {
console.log( "Filter:", item);
};
});
For more info about the . notation see here.
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>