Model not updated when view changes - angularjs

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

Related

AngularJs: Copy the data using ng-value but model does not update

I'm having an issue on updating or assigning the value or data into the model using ng-value.
I would like to copy any values in the DisplayName model to CopyDisplayName and using below directives i was able to do that, But the problem is the model CopyDisplayName doesn't have any value when I submit my changes. It can only have if I inputted it manually.
<input type="Text" ng-model="DisplayName" ng-disabled="true" />
<input type="Text" ng-model="CopyDisplayName" ng-value="DisplayName" />
Forgot to include that the DisplayName is disabled.. the data will came from service call.
ngValue
Binds the given expression to the value of or input[radio], so that when the element is selected, the ngModel of that element is set to the bound value.
You can take a look in this documentation.
So basically, the one you're doing right now will not work.
You can do this in your angular controller:
$scope.copyValue = function () {
$scope.copyDisplayName = $scope.displayName;
}
In html:
<input type="text" ng-model="displayName" ng-change="copyValue()" />
Just assign one variable to another:
// in the controller
$scope.CopyDisplayName = $scope.DisplayName;
If you need to keep them in sync (and for some reason, you don't want to just use the same variable), then you can keep them updated via ng-change:
<input type="Text" ng-model="DisplayName" ng-change="CopyDisplayName = DisplayName" />
Directives like ng-value (or ng-checked) only toggle the attributes in the DOM - they do not alter the View Model.
You can add $watch on DisplayName as:
$scope.$watch('DisplayName',function(newValue, oldValue){
console.log(newValue +":"+oldValue)
$scope.CopyDisplayName = newValue;
});
To have copy updated you need copy value by reference. For that you need to wrap displayName to object:
$scope.model = {DisplayName: 'val'}; and make a copy of it: $scope.modelCopy = $scope.model;
<input type="Text" ng-model="model.DisplayName" ng-disabled="true" />
<input type="Text" ng-model="modelCopy.DisplayName" ng-value="DisplayName" />
JSFiddle
what you can do in controller is watch the model and copy that value whenever it is changed($watch will do that for you) you dont need ngChange on the HTML.
$scope.$watch('displayName', function() {
$scope.copyDisplayName = $scope.displayName;
});

AngularJS - ngmodel in ngrepeat not updating ('dotted' ngmodel)

i'm trying to draw radioBoxes with angular array, and after that get value of checked radio, but model don't change its value you, can anyone help me with this ?
HTML part
<div ng-app>
<div ng-controller="CustomCtrl">
<label ng-repeat="user in users">
<input type="radio" name="radio" ng-model="radio" value="{{user.name}}" /> {{user.name}}
</label>
<br/>
{{radio}}
<br/>
Save
</div>
</div>
Angular Part
function CustomCtrl($scope) {
$scope.radio = "John";
$scope.users = [
{"name" : "John", "Year" : 18},
{"name" : "Tony", "Year" : 19}
];
$scope.saveTemplate = function() {
console.log($scope.radio);
};
}
you can see example here - http://jsfiddle.net/hgf37bo0/2/
you need to set $scope.radio to be an object like this:
$scope.radio = {
name: 'John'
}
and then access it from html like so:
<input type="radio" name="radio" ng-model="radio.name" value="{{user.name}}" />
here's a working jsfiddle
You can read up on why this is necessary in this answer
from angularjs docs:
Scope inheritance is normally straightforward, and you often don't even need to know it is happening... until you try 2-way data binding (i.e., form elements, ng-model) to a primitive (e.g., number, string, boolean) defined on the parent scope from inside the child scope. It doesn't work the way most people expect it should work. What happens is that the child scope gets its own property that hides/shadows the parent property of the same name. This is not something AngularJS is doing – this is how JavaScript prototypal inheritance works.
...
Having a '.' in your models will ensure that prototypal inheritance is in play. So, use
<input type="text" ng-model="someObj.prop1">
rather than
<input type="text" ng-model="prop1">
If you really want/need to use a primitive, there are two workarounds:
Use $parent.parentScopeProperty in the child scope. This will prevent
the child scope from creating its own property. Define a function on
the parent scope, and call it from the child, passing the primitive
value up to the parent (not always possible)

AngularJs multiple instances and nested controller

I got confused a bit about whether can we create multiple instance of controller and that to in nested form for eg -
<div ng-controller="abc">
<form ng-submit="call()">
<input type=text ng-model="content"/>
</form>
<div ng-controller = "abc">
<form ng-submit="call()">
<input type=text ng-model="content"/>
</form>
</div>
</div>
i just want to know that if i use the same model with other instance of controller, so model value would be same or different. Similar to static variable ?
i just want to know that if i use the same model with other instance
of controller, so model value would be same or different. Similar to
static variable ?
All declarations of ng-controller create a new instance of the controller. So, if you had two instances side by side, like this:
<div ng-controller="abc">
<input type=text ng-model="content"/>
</div>
<div ng-controller="abc">
<input type=text ng-model="content"/>
</div>
plunker
then, all of the $scope properties of each would be completely independent.
When a ng-controller is nested, then its scope inherits the parent controller's scope. So for this you'd expect that content refers to the same scope property:
<div ng-controller="abc">
<input type=text ng-model="content"/>
<div ng-controller="abc">
<input type=text ng-model="content"/>
</div>
</div>
plunker
However, since content is not defined directly in the controller something strange happens. If you fill in the parent input first. Both, inputs become bound to the same scope property. However, if you fill in the child input first, they are independent!
This can be confusing until you understand that Angular is being lazy when it creates the property on the scope. content is null at first on both scopes. It is only when it has a value that it will inherit.
So, what do you do if you want to keep things separate? Add an initial value to a $scope property inside the controller:
app.controller('abc', function($scope) {
$scope.content = '';
});
plunker
This way, each separate controller instance is initialized with its own content property.
Hope this helps.

How to prevent transcluding directive to create new child scope for the form directive?

I have a problem with directive transclude and the form directive. As you may know, the form will end up in the "scope" if you add the "name"-property to the form tag, then you can check for form validation and so on.
My problem start when i put the form tag in a directive that uses transclude. I'm aware of how to deal with this problem with two-way data binding, as mention here https://stackoverflow.com/a/14484903/1029874 -- "use an object instead of a primitive"
But my form ends up in the transcluding directives scope. Here is an example of what i want to do.
<div ng-controller="appCtrl">
<widget>
<widget-header>{{model.property}}</widget-header>
<widget-body>
<!-- The form will end up in "widget-body":s scope instead of appCtrl:s scope -->
<form name="appForm" ng-submit="submit()">
<input type="text" required ng-model="model.property" />
<input type="submit" value="submit" />
</form>
</widget-body>
</widget>
</div>
And here is the fiddle, http://jsfiddle.net/WLksJ/1/
Is there a way that I can get around this behavior?
Thanks!
An interesting question, but a problem that's easily avoided by using
<form name="appForm" ng-submit="submit(appForm.$valid)">
and checking the parameter in the submit function.
http://jsfiddle.net/udMJ7/
Another (perhaps better) option is to use this which is set to the scope of the last controller (in this case the form controller, which we want)
$scope.submit = function(){
if(this.appForm.$valid){
//post the form!!
}
};
http://jsfiddle.net/udMJ7/1/

How to bind 2 models to one input field in Angular?

Is there anyway that I can bind two model values to one input field?
Suppose I have input field which I want to be the value of two variables in the scope something like:
<input type="text" model="sn_number; id" >
You cannot, but there are some workarounds.
1. Use ngChange to update the other model
<input type="text"
ng-model="sn_number"
ng-change="id=sn_number"/>
2. You could watch a model, and when in changes, update another
$scope.$watch('sn_number', function(v){
$scope.id = v;
});
You would need to watch also for changes in id if you want to keep them in sync.
Example here
You can bind fields immediately, not only in ng-change, and actually it isn't data binding, its only angular expression
<label>Name</label>
<input type="text" ng-model="name" value="{{name}}"/>
<label>Key</label>
<input type="text" ng-model="key" value="{{key=name}}" />
It would make no sense to bind an input to two variables in the model. Binding works both ways, so if the model is updated, the field is updated and vice-versa. If you were to bind to two variables, what would be the single source of truth?
However you can use ng-change to call a method on the controller which can set two variables when the field changes.
with ng-init
<div ng-controller="ctrl" ng-init="model = { year: '2013', month:'09'}">
or
<div ng-repeat="c in contact" ng-init="likes = { food: 'steak', drink:'coke'}">

Resources