Angular JS - How can I get the ngModelController by its model name? - angularjs

In my custom directive, I need to update the validity of another input. The directive is something like this :
<customDirective="foo">, in which the value foo is the name of another ngModel.
In my direcitve, I can get its model by :
var foo = scope[attrs.foo];.
But how can I get its ngModelController, to set its validity? Just like this :
fooModelController.$setValidity('customDirective', true);
EDIT :
In html, the input is defined as :
<input type="text" name="dateDebut" id="dateDebut" class="form-control" ng-model="formData.dateDebut" customDirective="dateFin" required>
<input type="text" name="dateFin" id="dateFin" class="form-control" ng-model="formData.dateFin" customDirective="dateDebut" required>
I get the dom node by angular.element.find(document.querySelctor('#dateDebut'));

angular.element(document.querySelctor('#dateDebut')).controller('ngModel') -- this will give the ngModelController defined on #dateDebut element.
Here is the plnkr: http://plnkr.co/edit/qXyxEb2QHyhuRUttNMXn?p=preview

Related

There is no directive with "exportAs" set to "ngModel"

I am using angular 2 forms in my application and i have created the input based on my model. I have binded my input field with ngmodel and now I want to do a dirty check on this input field. So i have added input with # variable. Here is my code:-
<input type="text" [ngClass]="{red: sampledetails.rules[0].query3.dirty}" class="form-control" name="query3" id="query3" [(ngModel)]="sampledetails.rules[0].query3" #query3="ngModel">
But I am getting an error something like:-
There is no directive with "exportAs" set to "ngModel" ("="form-control" name="query3" id="query3" [(ngModel)]="sampledetails.rules[0].query3" [ERROR ->]#query3="ngModel">
Can anybody help me here..
You dont need to use #query3="ngModel" for angular.js 2,
so change
from
<input type="text" [ngClass]="{red: sampledetails.rules[0].query3.dirty}"
class="form-control" name="query3" id="query3"
[(ngModel)]="sampledetails.rules[0].query3" #query3="ngModel">
to (this will work)
<input type="text" [ngClass]="{red: sampledetails.rules[0].query3.dirty}"
class="form-control" name="query3" id="query3"
[(ngModel)]="sampledetails.rules[0].query3" >

Initializing the input form in AngularJS using value from scope variable

How do I initialize a form to values from other $scope variable in AngularJS?
I know that I have to use ng-init to achieve that but instead of initializing it to values I have to initialize that to value in the variable.
I have $scope.User containing all the details of the user, so when the data comes back I want that to fed into respective fields. For example $scope.User.FirstName gets fed into FirstName input field.
<label>FirstName:</label>
<input type="text" id="FirstName" required ng-model="newUser.FirstName" ng-init="newUser.FirstName='User.FirstName'"/>
The HTML element has to be defined as below.
<input type="text" ng-model="firstname">
Inside your angular controller, the JS code will be as below,
$scope.firstname = $scope.User.FirstName;
This will ensure that textbox will have a value displayed
In your HTML :
<input type="text" ng-model="User.firstname ">
<input type="text" ng-model="User.lastName ">
//other html elements
In your controller :
$scope.User= {
firstname : 'my first name',
lastName : 'my last name',
//..other data
}

Get ngModel value from $scope without it's exact name

What I need is to get value of my model from my directive
<input type="number"
placeholder="must be numeric"
class="form-control"
name="meter_count"
ng-model="sllr.entity.MeterCount"
is-number>
But I would like to get it dynamically, not like this: var mdl = scope.sllr.entity.MeterCount but this:var mdl = scope.myNgModel

Get "raw" value from invalid input field

I have an input field in a form with some validations. It works like a charm.
It basically looks like this:
<input
class="form-control"
type="number"
ng-model="zipcode"
ng-minlength="5"
ng-maxlength="5"
id="zipcode"
name="zipcode"
required
>
A working plunkr is here: http://plnkr.co/edit/H0h59kG75T5MGE9cAhSo?p=preview
But now I also want to react to every input change - whether valid or not. So for example if the input field contains "123" it is not valid and the value is not transferred to my model - thats fine. But I still want to get the value to do some intermediate requests to a webservice.
Any Ideas?
First call the form element in your controller, then use the $viewValue attribute :
View :
<form name="form">
<input
...
ng-model="zipcode"
ng-change="getRawValue(form)"
name="zipcode"
required
>
</form>
Controller:
$scope.getRawValue = function(form) {
var rawValue = form.zipcode.$viewValue;
}
Angular 1.3 introduced a real answer for this: allowInvalid in ngModelOptions.
Example:
<input
type="text"
name="userName"
ng-model="user.name"
ng-model-options="{allowInvalid: true}"
>
Here is what i came up with for your scenario.
Basically you can write a directive which requires ngModel (ngModelController). The ngModelController has a array of parsers which it call to parse the view value in a pipeline manner. If validation fail these parsers do not update the model. If you inject a custom parser at the start of this parsers array, you can get the each view change value and do anything you want with it.
See my plunkr here http://plnkr.co/edit/ruB42xHWj7dBxe885OGy?p=preview (See console)
The basic code would be
ngModelCtrl.$parsers.splice(0,0,(function (viewValue) {
console.log("The view value is:"+viewValue)
return viewValue;
}));
Also see ngModelController documenation

Model not updated when view changes

I have a form for creating new records in a partial which I load in my main view like this
<div ng-controller="NewProductController">
<ng-include src=" 'views/partials/product-form.html' "></ng-include>
</div>
In the form, I have some input fields
..
<input ng-model="cip" type="text" id="cip" class="form-control" placeholder="Enter the CIP" autofocus="autofocus"/>
<input ng-model="name" type="text" id="name" class="form-control" placeholder="Enter the name" />
And in my controller, I'm sending a POST request with the values of the input fields:
...
.controller('NewProductController', function(Product, $scope) {
$scope.create = function () {
Product.create( {'cip': $scope.cip,
'name': $scope.name,
'dosage': $scope.dosage,
...
});
};
The problem is that when the values of the input fields change, it is not reflected in the controller ($scope.cip and $scope.name are undefined unless I initialized them with some value) but when $scope.cip and $scope.name are changed in the controller, the changes are correctly reflected in the view.
I thought that kind of updates are automatic or am I missing something ?
The reason why this is happening because ng-include creates a child scope. Since you are managing the model fields in the child scope i.e inside the template html, the fields are not available on the parent scope, where your controller is defined.
To fix this issue first and foremost thing that you need to do would be to create a obj such as product and define it on the controller NewProductController scope.
$scope.product={};
The template then should bind to sub properties of this product object.
<input ng-model="product.cip" type="text" id="cip" class="form-control" placeholder="Enter the CIP" autofocus="autofocus"/>
Now your changes would be available in the parent product object.
You can improve it a bit by passing the product object using ng-init like this
<ng-include src=" 'views/partials/product-form.html' " ng-init='model=product'></ng-include>
Now your template input fields change to
<input ng-model="cip" type="text" id="model.cip" class="form-control" placeholder="Enter the CIP" autofocus="autofocus"/>
Advantage
You template is not dependent on the structure of parent model class. Dependency is explicit. The template becomes more reusable as it clearly defines the model it works with, like in your case the template works with Product model.
For the sake of completeness of the answer i must link to this must read article, Understanding Scopes

Resources