Bind ngModel to AngularJS directive with isolated scope - angularjs

I'm trying to build an Angular directive that renders radio inputs and the associated labels. The HTML for the directive looks like this:
<d-radio name="gender" value="male" label="I'm a male"></d-radio>
<d-radio name="gender" value="female" label="I'm a female"></d-radio>
I'd like it render the equivalent of this:
<input type="radio" name="gender" id="male" value="male" ng-model="gender"><label for="male">I'm a male</label>
<input type="radio" name="gender" id="female" value="female" ng-model="gender"><label for="female">I'm a female</label>
And here's the JS code:
app.directive('dRadio', function() {
return {
restrict: 'E',
scope: true,
template: '<input type="radio" id="{{value}}" name="{{name}}" value="{{value}}"><label for="{{value}}">{{label}}</label>',
link: function(scope, element, attrs) {
scope.name = attrs.name;
scope.value = attrs.value;
scope.label = attrs.label;
}
};
});
The only thing missing from my directive is the ng-model portion. Since each directive creates an isolated scope, I'm not sure how to bind the model to it.
There is a similar Stack Overflow question here:
Isolating directive scope but preserve binding on ngModel
I tried this solution, but I couldn't get it to work. Any ideas? Thanks!

If you want to have a bi-directional binding you will need to add an model: '=' to your scope. That will allow you to have a model variable in your scope which will be binded with the one you indicate in the html
app.directive('dRadio', function() {
return {
restrict: 'E',
scope: { model: '=' },
template: '<input type="radio" ng-model="{{model}}" id="{{value}}" name="{{name}}" value="{{value}}"> <label for="{{value}}">{{label}}</label>',
link: function(scope, element, attrs) {
scope.name = attrs.name;
scope.value = attrs.value;
scope.label = attrs.label;
}
};
});
And in your html
<d-radio name="gender" value="male" label="I'm a male" model="gender"></d-radio>

Related

Deselectable radio not tracking previous value correctly

I'm trying to create a simple directive that I can apply to an existing radio input to make it deselectable...it doesn't quite work as the directive is not tracking the previously clicked value correctly. The goal is to have the radio set to 'true', 'false', or null if the currently selected value is the same as the previous (clicking true twice for example will unset the radio and set the model value to null). It seems to continually lose track of the previous value which gets set to undefined. I think I'm maybe making some kind of scoping issue but I'm not sure.
Here is the directive:
angular.module('App').directive('deselectableRadio', function() {
return {
restrict: 'A',
scope: {
model: '=ngModel'
},
link: function(scope, element, attr) {
var previousValue = angular.copy(scope.model);
element.bind('click', function(e) {
determineState(element[0]);
});
function determineState(elem) {
if (elem.checked && elem.value == previousValue) {
elem.checked = false;
scope.model = null;
}
previousValue = angular.copy(scope.model);
}
}
}
});
And here is the HTML:
<div class="app-radio">
<input type="radio" name="toggle" id="toggle-yes" value="true"
ng-model="props['toggle']" deselectable-radio>
<label for="toggle-yes">Yes</label>
</div>
<div class="app-radio">
<input type="radio" name="toggle" id="toggle-no" value="false"
ng-model="props['toggle']" deselectable-radio>
<label for="toggle-no">No</label>
</div>
The directive is fighting the ng-model controller.
Instead of creating an isolate scope and a two-way binding to the ng-model attribute, use the ngModelController API.
The DEMO
angular.module('app',[])
.directive('deselectableRadio', function() {
return {
restrict: 'A',
scope: false,
//scope: {
// model: '=ngModel'
//},
require: "ngModel",
link: function(scope, element, attrs, ctrl) {
element.on('click', function(e) {
if (attrs.value == ctrl.$viewValue) {
ctrl.$setViewValue(null);
ctrl.$render();
}
});
}
};
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<div class="app-radio">
<input type="radio" name="toggle" id="toggle-yes" value="true"
ng-model="props['toggle']" deselectable-radio>
<label for="toggle-yes">Yes</label>
</div>
<div class="app-radio">
<input type="radio" name="toggle" id="toggle-no" value="false"
ng-model="props['toggle']" deselectable-radio>
<label for="toggle-no">No</label>
</div>
<br>
model = {{props.toggle || 'null'}}
</body>

angular 1.4 directive toggle view

I want to show two different inputs depending on a toggle attribute.
No I have the problem that I should define each attribute/property of the input in my directive, but the binding doesn't work.
Directive:
angular.module('directive')
.directive('inputBlock', function () {
return {
restrict: 'AEC',
replace: true,
scope: {
model: '=',
modernStyle:'=',
name:'=',
type:'=',
label:'='
},
link: function (scope, elem, attrs, ctrl) {},
templateUrl: 'views/templates/inputBlockTemplate.html'
};
});
Template:
<div>
<div ng-if="!modernStyle">
<label>{{label}}</label>
<input ng-model="model" name="{{name}}" type="{{type}}"/>
</div>
<md-input-container ng-if="modernStyle">
<label>{{label}}</label>
<input ng-model="model" name="{{name}}" type=" {{type}}"/>
</md-input-container>
</div>
Usage:
<input-block model="name" label="'firstname'" modern-style="true" name="'firstname'" type="'text'">
</input-block>
Is it possible to do something like a toggle in directives?
Furthermore is it possible to redirect the bindings to directives?
ng-if creates a new child scope, try change by ng-show/ng-hide
Understanding Scopes
Other considerations:
As you use name,label and type as text inside your directive is not necesary that it will be binding, I recomend use # instead of =, or access it directly from the attrs link argument.
The scope.model could be set as ngModel to use the default angular directive.
Javascript:
angular.module("directive").directive("inputBlock", function () {
return {
restrict: "AEC",
replace: true,
scope: {
ngModel: "=",
modernStyle:"#",
//name:"#",
//type:"#",
//label:"#"
},
link: function (scope, elem, attrs, ctrl) {
scope.type=attrs.type;
scope.name=attrs.name;
scope.label=attrs.label;
},
templateUrl: "views/templates/inputBlockTemplate.html"
};
});
Template:
<div>
<div ng-show="!scope.modernStyle">
<label>{{scope.label}}</label>
<input ng-model="scope.model" name="{{scope.name}}" type="{{scope.type}}"/>
</div>
<md-input-container ng-show="scope.modernStyle">
<label>{{scope.label}}</label>
<input ng-model="scope.model" name="{{scope.name}}" type={{scope.type}}"/>
</md-input-container>
</div>
Usage:
<input-block ng-model="name" label="firstname" modern-style="true" name="firstname" type="text">
</input-block>

Get access to form controller validation errors in a custom directive

I have a directive that wraps a form element with some inputs. One of the options is passing in a formName. Usually, with a form with the example name of myForm, to show an error you would do something like myForm.firstName.$error.required.
But, how do I get access to the errors when the form name is dynamically being passed in to the directive?
example usage
<my-custom-form formName='myForm' formSubmit='parentCtrl.foo()'></my-custom-form>
directive
angular.module('example')
.directive('myCustomForm', [
function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'myCustomForm.directive.html',
scope: {
fornName: '#',
formSubmit: '&'
},
require: ['myCustomForm', 'form'],
link: function(scope, element, attrs, ctrls) {
var directiveCtrl = ctrls[0];
var formCtrl = ctrls[1];
scope.data = {};
scope.hasError = function(field) {
// how do i show the errors here?
};
scope.onSubmit = function() {
scope.formSubmit();
};
}
};
}]);
template
<form name="{{ formName }}" ng-submit="onSubmit()" novalidate>
<div class="form-group" ng-class="{'is-invalid': hasError('fullName') }">
<input type="text" name="fullName" ng-model="data.full_name" required />
<div ng-show="hasError('fullName')">
<p>How do I show this error?</p>
</div>
</div>
<div class="form-group" ng-class="{'is-invalid': hasError('email') }">
<input type="text" name="email" ng-model="data.email" ng-minlength="4" required />
<div ng-show="hasError('email')">
<p>How do I show this error?</p>
</div>
</div>
<button type="submit">Submit</button>
</form>
I think the only problem with your code is that the directive requires itself, I don't think that will work. Just removing the myCustomForm from the require works fine.
To check if the field has errors, you just need to check if the $error object in the form controller is empty.
require: ['form'],
link: function(scope, element, attrs, ctrls) {
var formCtrl = ctrls[0];
scope.data = {};
scope.hasError = function(field) {
// Field has errors if $error is not an empty object
return !angular.equals({}, formCtrl[field].$error);
};
Plunker

ng-model is not bind with controller's $scope when I am creating a form dynamically using directive.

view code:- mydir is my custom directive
<div ng-model="vdmodel" mydir="dataValue">
</div>
my directive :-
app.directive('mydir',['$translate',function($translate){
return {
restrict: 'A',
transclude: true,
scope: {dir:'=mydir'},
compile: function(element, attrs) {
return function(scope, element, attrs, controller){
var setTemplate = '';
var setOpt = '';
if(scope.dir.itemtype== 'NUMBER'){
setTemplate = '<input type="number" class="form-control form-font ng-animate ng-dirty"';
setTemplate +='" ng-model="dir[somevalue]" value="'+scope.sizing.somevalue+'" >';
element.html(setTemplate);
}
}
}
}
});
There are many more form element in directive, but when I am trying to submit and collect value in my controller function I get nothing.
What I am doing wrong and what is the best way to collect form values ?
there are quiet a few changes that you will need to do
1.as you are using isolate scope, pass ngModel as well to the directive
scope: {dir:'=mydir', ngModel: '='},
2.as per the best practise ngModel must always have a dot
ng-model="params.vdmodel"
3.make sure to initialize the params object in controller
$scope.params = {}
Usually, a directive would share the same scope as the parent controller but since you are defining a scope in your directive, it sets up it's own isolate scope. Now since the controller and directive have their seperate scope, you need a way to share the data between them which is now done by using data: "=" in scope.
The app code
var myApp = angular.module('myApp', []);
myApp.controller('myController', function ($scope, $http) {
$scope.vdmodel = {};
})
.directive("mydir", function () {
return {
restrict: "A",
scope:{
data:"=model",
dir:'=mydir'
},
templateUrl: 'test/form.html'
};
});
The form.html
<form>
Name : <input type="text" ng-model="data.modelName" /><br><br>
Age : <input type="number" ng-model="data.modelAge" /><br><br>
Place : <input type="text" ng-model="data.modelPlace" /><br><br>
Gender:
<input type="radio" ng-model="data.modelGender" value="male"/>Male<br>
<input type="radio" ng-model="data.modelGender" value="female"/>Female<br><br><br>
</form>
The page.html
<div ng-app="myApp" >
<div ng-controller="myController" >
<div model="vdmodel" mydir="dataValue"></div>
<h3>Display:</h3>
<div>
<div>Name : {{myData.modelName}} </div><br>
<div>Age : {{myData.modelAge}}</div><br>
<div>Place : {{myData.modelPlace}}</div><br>
<div>Gender : {{myData.modelGender}}</div><br>
</div>
</div>
</div>
You have to use $compile service to compile a template and link with the current scope before put it into the element.
.directive('mydir', function($compile) {
return {
restrict: 'A',
transclude: true,
scope: {
dir: '=mydir'
},
link: function(scope, element, attrs, controller) {
var setTemplate = '';
var setOpt = '';
if (scope.dir.itemtype == 'NUMBER') {
setTemplate = '<input type="number" class="form-control form-font ng-animate ng-dirty"';
setTemplate += '" ng-model="dir.somevalue" value="' + scope.dir.somevalue + '" >';
element.html($compile(setTemplate)(scope));
}
}
}
});
See the plunker below for the full working example.
Plunker: http://plnkr.co/edit/7i9bYmd8blPNHch5jze4?p=preview

Angularjs: validation not working when control is based on directive

Being rather new to Angularjs, I am creating textbox-label combinations in Angularjs using directives. It's working very well, but I can't get validation to work. Here is a stripped-down example.
The Html:
<form name="form" novalidate ng-app="myapp">
<input type="text" name="myfield" ng-model="myfield" required />{{myfield}}
<span ng-show="form.myfield.$error.required">ERROR MSG WORKING</span>
<br>
<div mydirective FIELD="myfield2" />
</form>
The Javascript:
var myapp = angular.module('myapp', []);
myapp.directive('mydirective', function () {
return {
restrict: 'A',
scope: { ngModel: '=' },
template: '<input type="text" name="FIELD" ng-model="FIELD" />{{FIELD}}
<span ng-show="form.FIELD.$error.required">ERROR MSG NOT WORKING</span>'
};
});
The hard coded input - myfield - works, the other - myfield2 - doesn't (the binding does, just not the required-error message).
How do I tell the ng-show attribute to sort of "replace" FIELD in form.FIELD.$error.required by myfield2?
Here is a jsFiddle.
The problem is that your directive creates a new scope for the directive, this new scope does not have access to the form object in the parent scope.
I came up with two solutions, though I suspect there is a more elegant "Angular" way to do this:
Passing down the form object
Your view becomes:
<div mydirective FIELD="myfield2" form="form" />
And the scope definition object:
return {
restrict: 'A',
scope: {
ngModel: '=',
form: '='
},
template: '<input type="text" name="FIELD" ng-model="FIELD" required/>{{FIELD}}<span ng-show="form.FIELD.$error.required">ERROR MSG NOT WORKING</span>'
};
I've updated the fiddle with this code: http://jsfiddle.net/pTapw/4/
Using a controller
return {
restrict: 'A',
controller: function($scope){
$scope.form = $scope.$parent.form;
},
scope: {
ngModel: '='
},
template: '<input type="text" name="FIELD" ng-model="FIELD" required/>{{FIELD}}<span ng-show="form.FIELD.$error.required">ERROR MSG NOT WORKING</span>'
};

Resources