Execute if function if checkbox is checked angular.js - javascript

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.

Related

Unable to use ng-changeto call function

Hi had a small functionality where on change of number the value should be multiplied ..but now it is not working..
Can someone help me which is quite simple
Tag
<input type="number" class="form-control text-right" ng-model="totalPremium" ng-change="result()"></input>
Controller
$scope.result = function() => {
return $scope.totalPremium*5;
};
Thanks
Please look the jsfiddle
Module and App name is not set in your fiddle
Set module
angular.module('myapp', [])
.controller('TodoCtrl', TodoCtrl);
Set app name
<div ng-app="myapp">
Controller same as before
function TodoCtrl($scope) {
$scope.result = function() {
return $scope.totalPremium*5;
};
};
FIDDLE

AngularJS, how to trigger dom-related javascript on ng-if change

I have a form field (input text) with an ng-if being false at the begining. At some point the ng-if value become true.
When this happen, I want to execute some javascript which manipulate the DOM. To keep it simple, let's say that I need to select the input value and focus the field.
<input type="text" ng-value="foo" ng-if="show" onshow="doSomething()"/>
<button ng-click="toggle()"></button>
The JavaScript
ctrl.foo = "bar";
ctrl.show = false;
ctrl.toggle = function(){
ctrl.show = !ctrl.show;
}
I know that it looks like a "non-angular approach", but here I think the action is not model related.
Since the ng-if directive execute the template each time show become true, you can use ng-init for that. See the following snippet and replace alert('test); by anything you want.
angular.module('test', []).controller('test', function($scope, $element) {
$scope.show = false;
$scope.toggle = function() {
$scope.show = !$scope.show;
};
$scope.init = function() {
alert($element.find('input').val());
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test">
<div ng-controller="test">
<input type="text" value="foo" ng-if="show" ng-init="init()" />
<button ng-click="toggle()">Toggle</button>
</div>
</div>

Detect Input text length in angularjs

I am beginner in Angularjs
<div ng-app>
<input type="text" ng-model="Number"/>
</div>
I know can use {{Number.length}} to display input field length,
But how detect length
etc..
if (length == 0) {
// do something
} else if (length == 1) {
// do something
}
Any advice would be highly appreciated.
There are many ways to do this.
1. Using built-in directives + template
<div ng-app="app">
<input type="text" ng-model="Number"/>
<section ng-if="!Number">It's empty</section>
<section ng-if="Number">It's {{Number.length}}</section>
</div>
You could also use a controller or directive to achieve the same thing.
See some examples in action -> http://jsbin.com/vaxohi/4/edit
2. Using a controller
You can watch the value of Number in a controller, like so:
app.controller('AppCtrl', function($scope){
$scope.Number = '';
$scope.$watch('Number', function(newValue){
if(newValue.length === 0){
console.log('Empty');
} else {
console.log('Has content');
}
});
});
However, it's not a good practice to do it like this. The best way to do it is by using a directive.
3. Using a directive
Diretives can attach certain behavior to DOM elements; there are many built-in directives (ng-if, ng-show, etc), but it's very common to create custom ones. Here's an example:
app.directive('numberLogic', function(){
return {
restrict: 'A',
scope: {},
template: "<input type='text' ng-model='Number2'/> {{Number2}}",
link: function(scope){
scope.$watch('Number2', function(newValue){
if(newValue.length === 0){
console.log('Second number Empty');
} else {
console.log('Second number Has content');
}
});
}
};
});
By the way...
I see your ng-app directive is empty. Don't forget to pass in a module name for your app ng-app="appName" and define a module with the same name angular.module('appName', []); (See the jsbin).
you can use ng-change
for example
<input type="text" ng-model="Number"
ng-change="(Number.length>0)?alert('ok'):alert('no')"/>
or you can specify an function to be executed on change
<div ng-app="app">
<div ng-controller="test">
<input type="text" ng-model="Number"
ng-change="checkLength()"/>
</div>
</div>
And Js code
angular.module('app', [])
.controller('test',function($scope){
$scope.checkLength = function(Number){
if(Number.length>0){
//
}
}
})

Angular Radio Values in ng-repeat

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
}
}]);

Dynamically assign ng-model

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>

Categories

Resources