I have a controller who changes its view using 2 ng-include( tried both file and script). One for view and other for edit screen.
<div class="content-area">
<div class='row'>
<div class="cs-info">
<fp-info-bar config="headerConfig"></fp-info-bar>
<ng-include src="currentTemplate"></ng-include>
</div>
</div>
View template do not have inputs. The edit template have a form, 4 ng-form which them self contain inputs and custom directives.
<ng-form name='premisesAddressForm' attempt>
<div has-permission='CustomerDetailEditOverrideAddressValidation'>
<input type="checkbox" ng-model="isPremisesAutoCorrectDisabled"><span>Turn off Auto Correct</span>
</div>
<fp-address-edit
states="states"
ng-model='customer.PremisesAddress'
on-change="validateAddress(customer.PremisesAddress, premisesAddressForm, isPremisesAutoCorrectDisabled)">
</fp-address-edit>
</ng-form>
Data gets successfully populated and other things works fine too with in directive in edit mode.
Problem: When i try to save data on parent controller and check scope, i do not find any form(premisesAddressForm) or other input fields on edit template. i.e. this $scope.premisesAddressForm do not exist. Just to make clear, the save button is on same template and is bind to function on parent controller, no problems with that. I tried creating objects with in parent controller like this but no use.
$scope.forms = {};
<ng-form name='froms.premisesAddressForm' attempt>
I know ng-include create its own scope (inherit form parent) but i am not trying to get parent objects on child so no issues there. I also read some where that after ng-include changes, Angular compiles and updates the scope. To me there lies the problem. How i supposed to make it work? If my approach is wrong all together, please feel free to point out. My objective is to use same controller for different views, with different inputs or none. Thanks
You're correct that ngInclude creates a new child scope. The problem is that the parent scope will not have access to child scoped properties. What you could do is the same thing you tried, but instead of passing the form back to the parent controller, you should pass the values back.
In your parent controller:
$scope.myObj = {
customer: {}
};
In your template:
<ng-form name='premisesAddressForm' attempt>
<div has-permission='CustomerDetailEditOverrideAddressValidation'>
<input type="checkbox" ng-model="myObj.isPremisesAutoCorrectDisabled"><span>Turn off Auto Correct</span>
</div>
<fp-address-edit
states="states"
ng-model='myObj.customer.PremisesAddress'
on-change="validateAddress(myObj.customer.PremisesAddress, premisesAddressForm, myObj.isPremisesAutoCorrectDisabled)">
</fp-address-edit>
</ng-form>
If you need for the controllers to communicate during saving (e.g. kick off validation), you could use events.
Related
I am attempting to do something like this:
<div ng-form="testForm" ng-init="$ctrl.doStuffWithForm(testForm)>
Where I define a form/publish the form to the current scope with the name testForm and pass that form object to $ctrl.doStuffWithForm() in the ng-init. However, what appears to be happening is that, at the time of the ng-init, the form creation and/or the creation of testForm in the scope has not happened yet (other testing indicates to me that testForm does point to a form controller at a later point in the Angular lifecycle).
Is there any way for me to pass the form controller to a method in the ng-init like this? Or should I be doing it another way? Is there an attribute similar to ng-init, but that is used later in the lifecycle? What I am trying to do is basically an ng-repeat on an element with an ng-form, and pass each form to a controller method when each element is initialized.
Avoid using $ng-init directive. Simply assign the ng-form to a property of the $ctrl object:
<div ng-form="$ctrl.testForm">
{{$ctrl.testForm.$dirty}}
</div>
I was able to achieve my desired results by putting the ng-init in a child element of the ng-form element:
<div ng-form="testForm">
<div ng-init="$ctrl.doStuffWithForm(testForm)></div>
</div>
I was reading Angular js docs when I came across the issues mentioned related to using ng-model with directives like ng-include , ng-switch , and ng-view.The reason mentioned was child scope and parent scope but I was not able to understand it completely.
Also it was mentioned that issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-model.
Here's the link
Can anyone please explain it in less-technical language?
ng-include, ng-switch and ng-if creates child scope.
It means that if you create
<div ng-controller="MyCtrl">
<div id="innerDiv" ng-if="!something">
<input ng-model="model">
</div>
</div>`
the model will be created in scope created by the #innerDiv (because of using ng-if). It might be problematic if you want to use model value in the controller, because it won't be possible (Parent scope has no access to properties of child scope!).
The solution is to use $parent.model in <input ng-model="model">. Then the property will be changed in parent's scope and that is what you usually want to achieve.
However using $parent might look not good for someone, so better solution is to create a named model in the controller. The you can use it and follow the rule "always have a '.' in your ng-model." Child scope created by ng-if has access to parrent scope, so he can use already defined $scope.model and change $scope.model.text property.
Controller:
$scope.model = {};
Html:
<div ng-controller="MyCtrl">
<div id="innerDiv" ng-if="!something">
<input ng-model="model.text">
</div>
</div>`
(But remember that if you not define $scope.model in the controller, it would behave like in first example).
If you are not sure that you are in the same scopes, you can check it by displaying scope's $id. Simply add in html {{$id}} above ng-if (or ng-include, ng-switch) and inside.
<div ng-controller="MyCtrl">
scope id: {{$id}}
<div id="innerDiv" ng-if="!something">
child scope id:{{$id}}
</div>
<div>scope id again {{$id}}</div>
</div>`
Some examples:
https://jsfiddle.net/La90btfh/3/
So, I have e.g. this controller:
angular.module('example', []).controller('ctrl', function($scope) {
$scope.data = '' // Here, I want to know the element this property is binded to..
});
and the following markup:
<div ng-controller="ctrl">
...
<input type="text" ng-model="data" required>
...
</div>
Now how do I get the input-element inside controller by the bind? In other words, how do I get the element binded on $scope.data?
The better question is what are you trying to do? In angular a single element on your scope could be binded to multiple html elements through a variety of mechanisms so trying to find everything it influences is very difficult. On the upside, it's probably not necessary.
One of the major tenants of angular is that you should update your model and let your view take care of itself, that is, it's okay for the view to be dependent on the model, but the model should not be dependent on the view.
Here is my plnkr: http://plnkr.co/edit/n8cRXwIpHJw3jUpL8PX5?p=preview You have to click on a li element and the form will appear. Enter a random string and hit 'add notice'. Instead of the textarea text you will get undefined.
Markup:
<ul>
<li ng-repeat="ticket in tickets" ng-click="select(ticket)">
{{ ticket.text }}
</li>
</ul>
<div ui-if="selectedTicket != null">
<form ng-submit="createNotice(selectedTicket)">
<textarea ng-model="noticeText"></textarea>
<button type="submit">add notice</button>
</form>
</div>
JS part:
$scope.createNotice = function(ticket){
alert($scope.noticeText);
}
returns 'undefined'. I noticed that this does not work when using ui-if of angular-ui. Any ideas why this does not work? How to fix it?
Your problem lies in the ui-if part. Angular-ui creates a new scope for anything within that directive so in order to access the parent scope, you must do something like this:
<textarea ng-model="$parent.noticeText"></textarea>
Instead of
<textarea ng-model="noticeText"></textarea>
This issue happened to me while not using the ng-if directive on elements surrounding the textarea element. While the solution of Mathew is correct, the reason seems to be another. Searching for that issue points to this post, so I decided to share this.
If you look at the AngularJS documentation here https://docs.angularjs.org/api/ng/directive/textarea , you can see that Angular adds its own directive called <textarea> that "overrides" the default HTML textarea element. This is the new scope that causes the whole mess.
If you have a variable like
$scope.myText = 'Dummy text';
in your controller and bind that to the textarea element like this
<textarea ng-model="myText"></textarea>
AngularJS will look for that variable in the scope of the directive. It is not there and thus he walks down to $parent. The variable is present there and the text is inserted into the textarea. When changing the text in the textarea, Angular does NOT change the parent's variable. Instead it creates a new variable in the directive's scope and thus the original variable is not updated. If you bind the textarea to the parent's variable, as suggested by Mathew, Angular will always bind to the correct variable and the issue is gone.
<textarea ng-model="$parent.myText"></textarea>
Hope this will clear things up for other people coming to this question and and think "WTF, I am not using ng-if or any other directive in my case!" like I did when I first landed here ;)
Update: Use controller-as syntax
Wanted to add this long before but didn't find time to do it. This is the modern style of building controllers and should be used instead of the $parent stuff above. Read on to find out how and why.
Since AngularJS 1.2 there is the ability to reference the controller object directly instead of using the $scope object. This may be achieved by using this syntax in HTML markup:
<div ng-controller="MyController as myc"> [...] </div>
Popular routing modules (i.e. UI Router) provide similar properties for their states. For UI Router you use the following in your state definition:
[...]
controller: "MyController",
controllerAs: "myc",
[...]
This helps us to circumvent the problem with nested or incorrectly addressed scopes. The above example would be constructed this way. First the JavaScript part. Straight forward, you simple do not use the $scope reference to set your text, just use this to attach the property directly to the controller object.
angular.module('myApp').controller('MyController', function () {
this.myText = 'Dummy text';
});
The markup for the textarea with controller-as syntax would look like this:
<textarea ng-model="myc.myText"></textarea>
This is the most efficient way to do things like this today, because it solves the problem with nested scopes making us count how many layers deep we are at a certain point. Using multiple nested directives inside elements with an ng-controller directive could have lead to something like this when using the old way of referencing scopes. And no one really wants to do that all day!
<textarea ng-model="$parent.$parent.$parent.$parent.myText"></textarea>
Bind the textarea to a scope variable's property rather than directly to a scope variable:
controller:
$scope.notice = {text: ""}
template:
<textarea ng-model="notice.text"></textarea>
It is, indeed, ui-if that creates the problem. Angular if directives destroy and recreate portions of the dom tree based on the expression. This is was creates the new scope and not the textarea directive as marandus suggested.
Here's a post on the differences between ngIf and ngShow that describes this well—what is the difference between ng-if and ng-show/ng-hide.
Like in this question, I want to add .error on a form field's parent .control-group when scope.$invalid is true.
However, hardcoding the form name like in ng-class="{ error: formName.fieldModel.$invalid }" means that I can't reuse this in different forms, plus I'd rather not repeat this declaration everywhere.
I figured that a directive that looks something like this could work:
<div class="control-group" error-on="model1, model2">
<input ng-model="model1">
<input ng-model="model2">
</div>
So when either model1 or model2 is not valid, .control-group gets .error added.
My attempt here. Is it possible to access the models from the directive, given the model names?
If there's a better approach, I'd love to hear it too.
I don't think that writing a custom directive is necessery for this use-case as the ng-form directive was created exactly for situations like those. From the directive's documentation:
It is useful to nest forms, for example if the validity of a sub-group
of controls needs to be determined.
Taking your code as an example one would write:
<div class="control-group" ng-class="{ error: myControlGroup1.$invalid }>
<ng-form name="myControlGroup1">
<input ng-model="model1">
<input ng-model="model2">
</ng-form>
</div>
By using this technique you don't need to repeat expressions used in ng-model and can reuse this fragment inside any form.
You can also change the markup in the accepted answer to do without the nesting, since ng-form is also a class directive:
<div class="control-group ng-form" name="controlGroup11" ng-class="{ error: controlGroup1.$invalid }>
<input ng-model="model1">
<input ng-model="model2">
</div>
Final solution Fiddle
Inside your link function, you can get access to the formController. It has all of the controls. So the following will give your directive access to .$valid:
el.controller('form')[attrs.errorOn].$valid
However, I don't know how to watch that for changes. I tried watching attrs.errorOn (i.e., watch the ng-model property), but the watch doesn't trigger unless a valid value is input (because of the way Angular forms work... unless that value is valid, it is not assigned to the scope property set by ng-model.)
Fiddle.
Maybe someone can take this further...