How can I auto check elements in nested ng-repeat? - javascript

I have a div which contains ng-repeat elements. These ng-repeat elements are inter-related to each other. Elements of ng-repeat are having checkboxes. What I want is when the element of top ng-repeat is check it should auto check the elements in other ng-repeat. Below picture is showing the actual representation of elements and next pic is showing what actually I am trying to achieve.
I did try this but it is not working at all
<div actor-check-box ng-repeat="actor in actors">
<div create-connections class="actor\{{$index}}" >
<span><input class="checkbox-actor" type="checkbox" name="actor-checkbox" id="actor-checkbox\{{$index}}">\{{actor}}</span>
</div>
<div ng-repeat="activity in activities">
<div ng-if="actor == activity.id">
<div ng-repeat = "impact in activity.text" >
<div update-connections class="impact\{{$index}}actor\{{actors.indexOf(actor)}}" actor-id="actor\{{actors.indexOf(actor)}}">
<span><input class="checkbox-activity" type="checkbox" name="impact-checkbox" id="activity-checkbox\{{$index}}actor\{{actors.indexOf(actor)}}" activity-check-box>\{{impact}}</span>
</div>
<div ng-repeat="feature in features">
<div ng-if="actor == feature.id && impact == feature.key">
<div feature-connection ng-repeat = "feature in feature.text" class="feature\{{$index}}" activity-id="impact\{{activity.text.indexOf(impact)}}actor\{{actors.indexOf(actor)}}" id="">
<span><input class="checkbox" type="checkbox" name="impact-checkbox" id="" >\{{feature}}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Directive code:
angular.module('mainModule').directive('activityCheckBox', function($interval) {
return {
restrict: 'EA',
/*replace: false,*/
scope: {
ngModel:'='
}
/*require: 'createConnections','updateConnections', 'featureConnection'*/,
/*transclude: true,*/
link: function(scope, element, attrs) {
element.find('input[type="checkbox"]').prop('checked',true);
}
};
});
angular.module('mainModule').directive('actorCheckBox', function($interval) {
return {
restrict: 'EA',
/*transclude: true,*/
link: function (scope, element, attrs, ctrl) {
console.log(element);
scope.$watch('ngModel', function(newValue){
element.find('input[type="checkbox"]').prop('activityCheckBox',true).trigger('change');
});
}
}
});

This cannot be implemented using the normal way we follow to check and uncheck elements. I used emit and brodcast inside the directive by capturing the dom. Here is the code I wrote and it works like a charm:
angular.module('mainModule').directive('allCheckboxesBroadcast', function($interval) {
return {
restrict: 'A',
controller: function($scope) {
$scope.checkAll = function (model,id) {
if (model == true){
$scope.$broadcast('allCheckboxes',id, true);
}else{
$scope.$broadcast('allCheckboxes',id, false);
}
}
}
};
});
angular.module('mainModule').directive('allCheckboxesListeners', function($interval) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('actorId', function(value) {
scope.$on('allCheckboxes', function(event, id,shouldCheckAllCheckboxes) {
actorId = 'actor' + id;
if (value == actorId){
element.find('input').prop('checked', shouldCheckAllCheckboxes);
$scope.$broadcast('featureCheckboxesListeners', actorId, true);
}
});
});
}
};
});

Related

Focus on empty ng-model data after ng-readonly=true

I have a form input. When the page is loaded the input has "ng-readonly=true" property and it only shows the data.
When I double click (ng-dblclick) the property "ng-readonly" changes to false and I can edit the input.
For all this, it is working currectly. But when the data
(ng-model="school.fax") a row data is empty it does do a focus, and I need to click on the input to focus and start writing.
It does not happen when the data is not empty (ng-model="school.fax" have value, get value from server API) and in this case, it's working correctly
The question:
How can I focus on the empty input and start writing without need to click the input row?
The code:
HTML
<label>
<input class="inputs"
type="text"
ng-readonly="!edit_school_fax"
ng-dblclick="editSchoolFax(true)"
ng-model="school.fax"/>
</label>
JS
$scope.editSchoolFax = function(edit) {
$scope.edit_school_fax = edit;
};
FYI
I try, and it does not work for me:
Add "autofocus" inside the input
<input autofocus
Use directive like this solution: LINK
add custom directive
link(scope, element, attrs) {
scope.$watch(attrs.someAttrs, (newVal, oldVal) => {
if (newVal === true && newVal !== oldVal) {
$timeout(() => {
element
.focus()
.select();
});
}
});
},
Use a custom directive that adds a focus method to the ngModelController:
app.directive("inputFormFocus", function() {
return {
require: "ngModel",
link: postLink
};
function postLink (scope, elem, attrs, ngModel) {
console.log("postLink");
console.log(ngModel);
ngModel.focus = function() {
elem[0].focus();
}
}
})
Usage
<form name="form1">
<input input-form-focus
name="fax"
class="inputs"
type="text"
ng-readonly="!edit_school_fax"
ng-dblclick="editSchoolFax(true)"
ng-model="school.fax"/>
</form>
$scope.form1.fax.focus();
The DEMO
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.editSchoolFax = function(edit) {
$scope.edit_school_fax = edit;
};
$scope.school = { fax: "555-100-1234" };
$scope.faxFocus = function() {
$scope.edit_school_fax = true;
$scope.form1.fax.focus();
};
})
.directive("inputFormFocus", function() {
return {
require: "ngModel",
link: postLink
};
function postLink (scope, elem, attrs, ngModel) {
ngModel.focus = function() {
console.log(attrs.name + " focus");
elem[0].focus();
}
}
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
<form name="form1">
<input input-form-focus
name="fax"
class="inputs"
type="text"
ng-readonly="!edit_school_fax"
ng-dblclick="editSchoolFax(true)"
ng-model="school.fax"/>
</form>
<button ng-click="faxFocus()">Focus and Edit</button>
</body>

Number validation in range in AngularJS

I am creating a project using AngularJS and I want to integrate validation in AngularJS. My requirement is that the number should be between the 1-4096 in AngularJS.
Here is my code:
<div class="col-lg-6 col-md-6">
<input type="text" class="form-control" placeholder="VLAN ID" ng-model="exchange.vlanId" valid-number/>
</div>
You should create very simple directive that would allow to validate input in reusable, configurable and declarative way.
You already have valid-number attribute, so the implementation can look like:
angular.module('demo', []).directive('validNumber', [function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
if (!ctrl) return;
var range = attrs.validNumber.split(',').map(Number);
ctrl.$validators.validNumber = function(value) {
return value >= range[0] && value <= range[1];
};
}
};
}]);
.error {color: brown;}
<script src="https://code.angularjs.org/1.4.8/angular.min.js"></script>
<div ng-app="demo">
<form name="form">
<input type="text" class="form-control" placeholder="VLAN ID" name="vlanId"
ng-model="exchange.vlanId" valid-number="1,4096" />
</form>
<div class="error" ng-show="form.$dirty && form.vlanId.$error.validNumber">VLAN ID should be in range 1-4096.</div>
</div>
You can bind an event on the input and call a function with passing the model in it:
<input type="text" class="form-control" placeholder="VLAN ID"
ng-model="exchange.vlanId"
ng-keydown="obj.validate(exchange.vlanId)" valid-number/>
Now in the controller you can define a method:
yourApp.controller('theController', ['$scope', function($scope){
$scope.obj = {
validate:function(val){
if(val < 1 || val > 4096){
alert(val+' is out of range');
}
}
};
}]);
And the directive valid-number can also be used:
yourApp.directive('validNumber', function($scope){
return {
restrict:'E',
link:function(scope, el, attrs){
el.on('keydown', function(){
el.css('border', function(){
return scope.exchange.vlanId < 1 || scope.exchange.vlanId > 4096
? "red" : "green";
});
});
}
};
});

Directive to accept numbers greater than 0 and less than 100

I am trying to create an angular Directive which returns an error when the input of the textfield is less than 5 and greater than 200 i am trying with this code and for some reason it isnt working any help would be appreciated.
JS
app.directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
// this next if is necessary for when using ng-required on your input.
// In such cases, when a letter is typed first, this parser will be called
// again, and the 2nd time, the value will be undefined
if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(/[^0-9]/g, '');
console.log("inputValue"+inputValue);
if(parseInt(inputValue) > 200 || parseInt(inputValue) < 5){
return '';
}
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
HTML
<div ng-controller="MyCtrl">
<input type="text" ng-model="number" required="required" numbers-only="numbers-only" />
</div>
The plunker that i created is this (http://plnkr.co/edit/QKifStiFmHBF8GhcH3Ds?p=preview)
Any help would be appreciated!
I have given a directive that takes care of your model value to always contain int values between 5 and 200. A 'ng-invalid' class will be added when you do setValidity to false. Using that you can use css to display error to the user. In case you want your input to be updated with the correct model value in case of error, you can do it in the blur event.
app.directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if(parseInt(inputValue) <= 200 && parseInt(inputValue) >= 5){
modelCtrl.$setValidity('numbersOnly', true);
return inputValue;
} else {
modelCtrl.$setValidity('numbersOnly', false);
return modelCtrl.$modelValue;
}
});
}
};
});
angular already has perfect directives for that. all you need is a form and use Min Max inside input tag
<form name="ue.form">
<input type="number" ng-model="ue.num" name="num" min="5" max="200" >
</form>
<p ng-if="ue.form.$error">
number must be less than 200 and greater than 5
</p>
or you can handle each error separately:
<p ng-if="ue.form.num.$error.min">
number must be greater than 5
</p>
<p ng-if="ue.form.num.$error.max">
number must be less than 200
</p>
if number is not in range 5-200 then form validotor throw an error.
min and max work only with input type="number".
https://plnkr.co/edit/?p=preview
Here's what I would suggest:
Use ng-model-options="{ updateOn: 'blur' }" so that model gets updated only on blur.
Try this code in directive:
app.directive('numbersOnly', function(){
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, ngModel) {
element.on('blur', function() {
if (ngModel.$viewValue < 5 || ngModel.$viewValue > 200) {
ngModel.$setViewValue('');
element.val('');
}
});
}
};
});
You can use ng-messages for these kind of validation purposes
We always can customize ng-messages with our needs.
you can create two directives for min and max. In your case your minimum value is 5 and max is 200, we dont need to hardcode our values inside the directives.
You dont need to worry for adding error messages in your directive. ng-messages will do it for you. You just need to put your messages inside ng-messages div.
Directive
module.directive("min", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attributes, ngModel) {
ngModel.$validators.min = function (modelValue) {
if (!isNaN(modelValue) && modelValue !== "" && attributes.min !== "")
return parseFloat(modelValue) >= attributes.min;
else
return true;
}
}
};
});
module.directive("max", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attributes, ngModel) {
ngModel.$validators.max = function (modelValue) {
if (!isNaN(modelValue) && modelValue !== "" && attributes.max !== "")
return parseFloat(modelValue) <= attributes.max;
else
return true;
}
}
};
});
Usage
<form name="myform">
<input type="text" name="minmax" ng-model="number" required="required" min="5" max="200"/>
<div data-ng-messages="myform.minmax.$error" class="error-messages">
<div data-ng-message="min">YOu cant enter below 5</div>
<div data-ng-message="max">You cant enter above 200</div>
</div>
</form>
Here is my pluker example

AngularJs Directive get radio button ng-model value on change

I have created an Angular js Directive that loops through ng-repeat and if users chooses any of those radio button, it should alert the current ng-model value.
But its not working. Please help.
var someapp = angular.module('someapp', []);
someapp.controller('someappCtrl', function($scope, $http) {
//...
}).directive('checkthemChoice', function() {
return {
restrict: 'A',
template: '<label ng-repeat="choice in choices" for="{{ choice }}"><input type="radio" ng-checked="$first" name="selecttable" ng-model="radioSelected" value="{{ choice }}" id="{{ choice }}"> {{ choice }}</label>',
link: function(scope, element, attrs) {
scope.choices = ['organization', 'user'];
element.on('change', function() {
//this selected the parent DIV checkthem
//but I want select the radio input inside LABEL
});
scope.$watch('radioSelected', function(val) {
//this doesnt work
alert(val);
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="someapp" ng-controller="someappCtrl">
<div class="checkthem" checkthem-Choice=""></div>
</div>
This works.
radioSelected needs to be a property of an object (for example, test). The explanation is given here https://github.com/angular/angular.js/wiki/Understanding-Scopes
Also, I have a put a test for undefined in the watch to avoid the first alert on load.
var someapp = angular.module('someapp', []);
someapp.controller('someappCtrl', function($scope, $http) {
//...
}).directive('checkthemChoice', function() {
return {
restrict: 'A',
template: '<label ng-repeat="choice in choices" for="{{ choice }}"><input type="radio" ng-checked="$first" name="selecttable" ng-model="test.radioSelected" value="{{ choice }}" id="{{ choice }}"> {{ choice }}</label>',
link: function(scope, element, attrs) {
scope.choices = ['organization', 'user'];
scope.test = {};
element.on('change', function() {
//this selected the parent DIV checkthem
//but I want select the radio input inside LABEL
});
scope.$watch('test.radioSelected', function(val) {
if (val !== undefined) alert(val);
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="someapp" ng-controller="someappCtrl">
<div class="checkthem" checkthem-Choice=""></div>
</div>

Custom directive to assign property on element

I used this snippet so I could see a "$touched" property on an input after it was blurred so I could do some validation, and it works great, but now I'm trying to make it work without overloading input and I've changed it to this:
.directive('blur', function () {
return {
restrict: 'E',
require: '?ngModel',
replace: true,
template: "<input />",
link: function postLinkFn($scope, $element, $attrs, ctrl) {
if (!ctrl) { return; }
ctrl.untouched = true;
ctrl.touched = false;
$element.on('blur', function (){
$scope.$apply(function () {
ctrl.untouched = false;
ctrl.touched = true;
});
});
}
};
});
Hoping to be able to use "myForm.email.touched", but that doesn't work. Is there something I'm doing wrong?
Your code works fine.
Maybe your html code is somehow wrong.
Here is how I made it work:
<div ng-app="app">
{{ myForm.email }}
<form name="myForm">
<blur type="email" ng-model="test" name="email" required></blur>
</form>
</div>
DEMO

Categories

Resources