ng-form nested within ng-switch - angularjs

I ran into an issue with ng-form not setting up the form on scope when its nested within an ng-scope.
For example
<div ng-controller='TestCtrl'>
<ng-switch on="switchMe">
<div ng-switch-default>Loading...</div>
<div ng-switch-when="true">
<form name="nixTest">
<input placeholder='In switch' ng-model='dummy'></input>
<button ng-click="test()">Submit</button>
</form>
</div>
</ng-switch>
</div>
Controller:
controllers.TestCtrl = function ($scope) {
$scope.switchMe = true;
$scope.test = function () {
if ($scope.nixTest) {
alert('nixTest exists')
} else {
alert('nixTest DNE')
}
}
}
Are there any work arounds to this ? Test fiddle can be found here

ng-switch creates a child scope and the form is created on this scope. Hence the child scope form would not be available on the parent scope.
To get access to it, you can pass it to the method test() like ng-click=test(nixTest). So the scope method signature would also need to updated to support the input parameter.

I ran into the same issue. Unfortunately I could not easily apply Chandermani's solution, because I need to access the form name from an $on call, within the ng-switch parent scope.
Thus, I resorted to creating a directive that sends the form's name to the $rootScope:
.directive("globalName", ["$rootScope", function($rootScope) {
return function(scope, element) {
$rootScope["get_" + element.attr('name')] = function() {
return scope[element.attr('name')];
};
}
}]);
Usage is like this:
<form name="whatever" novalidate global-name>...</form>
and then you access the form in controllers e.g. like this:
$scope.get_whatever().$setPristine();
$scope.get_whatever().$setUntouched();
Being the name in the $rootScope, it does not depend anymore on your DOM structure.
I understand this is not an optimal solution, as it pollutes the global namespace, but either I feel uncomfortable with form name visibility depending on the DOM structure, in somewhat unexpected ways.

Related

How to avoid using `$parent.$parent.$parent` in nested scopes

How can I know the Parent controller name in controller chain of Angular?
I'm new to Angular so I have one basic question.
Suppose, In Angular, I have a controller's chain like below.
<div ng-controller="parentController">
... something in the parent element
<div ng-controller="childController">
... something in the child element
</div>
</div>
Is there any way to write the code in the child element so that I can know the parent controller name in the output (In this case output should be 'parentController')?
I need this because I have a too big project and want to know the parent of each controller because someone has wrote the code like
googleOAuth= $scope.$parent.$parent.$parent.$parent.status.googleOAuth
and I'm not able to understand so want to know the parent of each $scope.
On approach is to use "controller as" syntax:
<div ng-controller="parentController as top">
<!-- ... something in the parent element -->
<div ng-controller="childController">
<!-- ... something in the child element -->
{{top.status.googleOAuth}}
</div>
</div>
This requires the controller be written using the this context instead of $scope.
Another approach is to use a property of an object in the parent scope:
app.controller("parentController", function($scope) {
$scope.top = {status: {} };
$scope.top.status.googleOAuth = value;
});
<div ng-controller="parentController">
<!-- ... something in the parent element -->
<div ng-controller="childController">
<!-- ... something in the child element -->
{{top.status.googleOAuth}}
</div>
</div>
Because scopes use prototypical inheritance, the top property is available to child scopes.
See AngularJS Developer Guide - Scope Hierarchies.
As georgeawg said, using $parent is not optimal because it relies on a constant number of scopes.
Instead, you could write a service to deal with your googleOAuth.
The service can then be injected in each controller and will function as a single source of truth because services are singletons in AngularJS.
e.g. something like this
angular.module('appModule', [])
.factory('googleOAuthService', [function() {
var googleOAuth = {
// your googleOAuth stuff here
};
return {
get: get,
set: set,
stuff: stuff
}
function get () {
return googleOAuth;
}
function set (newGoogleOAuth) {
googleOAuth = newGoogleOAuth;
}
function stuff () {
// Do stuff to googleOAuth
}
}])
.controller('parentController', ['googleOAuthService', function(googleOAuthService) {
googleOAuthService.stuff();
}])
.controller('childController', ['googleOAuthService', function(googleOAuthService) {
googleOAuthService.stuff();
}]);
For more info, see https://docs.angularjs.org/guide/services

How to change value of scope within a function - Why is my code not working?

Simple ng-class binding is not triggered when called inside a function, how can I resolve this?
$scope.afterHide = function() {
$scope.inputState = "fade-in";
}
<label ng-class="inputState">Next statement</label>
Works fine in this example:
angular.module("app",[])
.controller("ctrl", function($scope) {
$scope.afterHide = function() {
$scope.inputState = "fade-in";
};
$scope.reset = function() {
$scope.inputState = "";
};
});
.fade-in {
background-color: red;
}
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app="app" ng-controller="ctrl">
<label ng-class="inputState">Next statement</label>
<br><button ng-click="afterHide()">Invoke afterHide</button><br>
<button ng-click="reset()">Reset</button>
</div>
If it works then I think it has something to do with the overall logic of my code. The function $scope.afterHide is triggered by an event on one of the directives, this directive is defined outside the controller. In html its basically just another div that has a state of change. When a change happens, other elements on the page will also be affected, in this context, that other element is the label tag. When the change happens, the $scope.afterHide function within the controller is called by the directive which is defined outside of the controller.
Scopes are arranged in hierarchical structure which mimic the DOM structure of the application.
The ng-click directive cannot invoke a function on a scope that is outside its hierachy. Also if the ng-click directive is on a template inside a directive that uses isolate scope, the event must be connected to parent scope with expression, "&", binding.
For more infomation, see
AngularJS Developer Guide - Scopes
AngularJS Developer Guide - Directives (Isolating a Scope)

How to pass string and bool variables automatically to directive parent scope

I bind variable in a directive like this :
<path-filter-modal is-opened="filterModalIsOpened">
And in the directive I use '=' binding like this:
scope: {
isOpened: '='
}
When I change variable in directive, a parent scope contains own value.
How can I make that the parent scope contain the same value?
For objects it works well but not with strings and booleans.
Notice that I use controller that is defined in my directive in my directive to change values.
Because JavaScript is designed to be so.
Defining an isolate scope in the directive creates a new $scope object, which is a separate $scope object. Its only relationship with the parent scope is that: $isolateScope.$parent === $parentScope. It doesn't inherits from $parentScope prototypical.
When you assign some primitive type (string/boolean) to $scope.isOpened, actually JavaScript engine will create a new variable isOpened on $scope. It is totally not related to $parentScope.isOpened.
But now, Angular syncs the two variables for you implicitly. So binding primitive variables still makes two-way binding work well. Please check JSFiddle.
If you binds to some object type, the child scope and parent scope are referencing to the exactly the same copy of an object in the memory. Changing on the parent scope will change the child scope automatically. So two-way binding is always recommended to bind objects, not primitive types.
Check this JSFiddle. I bind a primitive and an object to the directive myDirective. Then modify them inside the link function:
scope.primitiveParam = 'primitive from directive';
// $parent.primitive and primitiveParam refer to different memory;
// Angular is responsible to sync them.
console.log(scope.$parent.primitive);
console.log(scope.primitiveParam);
scope.objectParam.name = 'object from directive';
// $parent.obj and objectParam refer to an identical object
console.log(scope.$parent.obj.name);
console.log(scope.objectParam.name);
console.log(scope.objectParam === scope.$parent.obj);
And the result is like:
primitive from parent
primitive from directive
object from directive
object from directive
For more details: Understanding Scopes (here are many intuitive images illustrating the concepts clearly)
RE: For objects it works well but not with strings and booleans
I think it's the usual case of prototypal inheritance problem. When the model come from object it works well, but if it come from non-objects there's a possibility that the ng-model is created on child scope.
To solve that problem, use modern approach, use Controller as approach. Or put the filterModelIsOpened in an object. The first approach is better.
<div ng-controller="SomeController as s">
<path-filter-modal is-opened="s.filterModalIsOpened">
</div>
function SomeController() { // no need to use $scope
this.filterModalIsOpened = false;
}
Or if you are using older version of Angular, you cannot use Controller as approach. Just create your own alias in the controller:
<div ng-controller="SomeController">
<path-filter-modal is-opened="s.filterModalIsOpened">
</div>
function SomeController($scope) {
$scope["s"] = this;
this.filterModalIsOpened = false;
}
Here's a good article explaining the prototypal inheritance: http://codetunnel.io/angularjs-controller-as-or-scope/
Here are the demo why you should always prefix your model, be they are object or primitive.
Not recommended. Live code demo: http://jsfiddle.net/hdks813z/1/
<div ng-app="App" ng-controller="Ctrl">
<div ng-if="true">
<input type="checkbox" ng-model="filterModalCanBeOpened"/>
<the-directive primitive-param="filterModalCanBeOpened"></the-directive>
</div>
<hr/>
<p>
The value below doesn't react to changes in primitive(non-object) property
that is created a copy on a directive(e.g., ng-repeat, ng-if) that creates
child scope
</p>
$scope.primitive: {{filterModalCanBeOpened}}
</div>
angular.module('App', [])
.directive('theDirective', function () {
return {
restrict: 'AE',
scope: {
primitiveParam: '='
},
template: '<div>primitiveParam from directive: {{ primitiveParam }}; </div>',
link: function (scope) {
}
};
})
.controller('Ctrl', ['$scope', function ($scope) {
$scope.filterModalCanBeOpened = true;
}]);
Recommended: Live code demo: http://jsfiddle.net/2rpv27kt/
<div ng-app="App" ng-controller="Ctrl as c">
<div ng-if="true">
<input type="checkbox" ng-model="c.filterModalCanBeOpened"/>
<the-directive primitive-param="c.filterModalCanBeOpened"></the-directive>
</div>
<hr/>
<p>
The value below react to changes in primitive(non-object) property that is
addressed directly by its alias c, creating child scope on it would be
impossible. So the primitive below react to changes on
the c's filterModalCanBeOpened.
</p>
c.primitive: {{c.filterModalCanBeOpened}}
</div>
angular.module('App', [])
.directive('theDirective', function () {
return {
restrict: 'AE',
scope: {
primitiveParam: '='
},
template: '<div>primitiveParam from directive: {{ primitiveParam }}; </div>',
link: function (scope) {
}
};
})
.controller('Ctrl', [function () {
this.filterModalCanBeOpened = true;
}]);

AngularJs can't access form object in controller ($scope)

I am using bootstrap-ui more specifically modal windows. And I have a form in a modal, what I want is to instantiate form validation object. So basically I am doing this:
<form name="form">
<div class="form-group">
<label for="answer_rows">Answer rows:</label>
<textarea name="answer_rows" ng-model="question.answer_rows"></textarea>
</div>
</form>
<pre>
{{form | json}}
</pre
I can see form object in the html file without no problem, however if I want to access the form validation object from controller. It just outputs me empty object. Here is controller example:
.controller('EditQuestionCtrl', function ($scope, $modalInstance) {
$scope.question = {};
$scope.form = {};
$scope.update = function () {
console.log($scope.form); //empty object
console.log($scope.question); // can see form input
};
});
What might be the reasons that I can't access $scope.form from controller ?
Just for those who are not using $scope, but rather this, in their controller, you'll have to add the controller alias preceding the name of the form. For example:
<div ng-controller="ClientsController as clients">
<form name="clients.something">
</form>
</div>
and then on the controller:
app.controller('ClientsController', function() {
// setting $setPristine()
this.something.$setPristine();
};
Hope it also contributes to the overall set of answers.
The normal way if ng-controller is a parent of the form element:
please remove this line:
$scope.form = {};
If angular sets the form to your controllers $scope you overwrite it with an empty object.
As the OP stated that is not the case here. He is using $modal.open, so the controller is not the parent of the form. I don't know a nice solution. But this problem can be hacked:
<form name="form" ng-init="setFormScope(this)">
...
and in your controller:
$scope.setFormScope= function(scope){
this.formScope = scope;
}
and later in your update function:
$scope.update = function () {
console.log(this.formScope.form);
};
Look at the source code of the 'modal' of angular ui bootstrap, you will see the directive has
transclude: true
This means the modal window will create a new child scope whose parent here is the controller $scope, as the sibling of the directive scope. Then the 'form' can only be access by the newly created child scope.
One solution is define a var in the controller scope like
$scope.forms = {};
Then for the form name, we use something like forms.formName1. This way we could still access it from our controller by just call $scope.forms.formName1.
This works because the inheritance mechanism in JS is prototype chain. When child scope tries to create the forms.formName1, it first tries to find the forms object in its own scope which definitely does not have it since it is created on the fly. Then it will try to find it from the parent(up to the prototype chain) and here since we have it defined in the controller scope, it uses this 'forms' object we created to define the variable formName1. As a result we could still use it in our controller to do our stuff like:
if($scope.forms.formName1.$valid){
//if form is valid
}
More about transclusion, look at the below Misco's video from 45 min. (this is probably the most accurate explanation of what transcluded scopes are that I've ever found !!!)
www.youtube.com/watch?v=WqmeI5fZcho
No need for the ng-init trickery, because the issue is that $scope.form is not set when the controller code is run. Remove the form = {} initialization and get access to the form using a watch:
$scope.$watch('form', function(form) {
...
});
I use the documented approach.
https://docs.angularjs.org/guide/forms
so, user the form name, on "save" click for example just pass the formName as a parameter and hey presto form available in save method (where formScopeObject is greated based upon the ng-models specifications you set in your form OR if you are editing this would be the object storing the item being edited i.e. a user account)
<form name="formExample" novalidate>
<!-- some form stuff here -->
Name
<input type="text" name="aField" ng-model="aField" required="" />
<br /><br />
<input type="button" ng-click="Save(formExample,formScopeObject)" />
</form>
To expand on the answer by user1338062: A solution I have used multiple times to initialize something in my controller but had to wait until it was actually available to use:
var myVarWatch = $scope.$watch("myVar", function(){
if(myVar){
//do whatever init you need to
myVarWatch(); //make sure you call this to remove the watch
}
});
For those using Angular 1.5, my solution was $watching the form on the $postlink stage:
$postLink() {
this.$scope.$watch(() => this.$scope.form.$valid, () => {
});
}

Angular Directive's template binding doesn't update

I have a directive set up here http://jsfiddle.net/screenm0nkey/8Cw4z/3 which has two bindings to the same scope property, but for some reason the binding in the directive's template property doesn't update when the model changes (after typing in the input).
<test>
<h3>Inner {{count}}</h3>
<input type="text" ng-model="count">
</test>
var App = angular.module('App', []);
App.directive('test', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
template: "<h1>Outer{{count}} <div ng-transclude></div></h1>",
controller: function ($scope) {
$scope.count = 1;
}
};
});
But if I move the input position in the markup it works and both bindings update.
<input type="text" ng-model="count">
<test>
<h3>Inner {{count}}</h3>
</test>
http://jsfiddle.net/screenm0nkey/dCvZk/3
Can anyone explain why the position of the input containing the binding, would have an affect the bindings. I assumed that during the digest loop the watchers for both binding would be updated regardless of the position of the markup.
Many thanks
To me, this seems purely to be a scope issue. Lets take a look at the markup that is generated by both:
Not working:
<body ng-app="App" class="ng-scope">
<h1 class="ng-binding">Outer1 <div ng-transclude="">
<h3 class="ng-scope ng-binding">Inner 1</h3>
<input type="text" ng-model="count" class="ng-scope ng-pristine ng-valid">
</div>
</h1>
</body>
Working:
<body ng-app="App" class="ng-scope">
<input type="text" ng-model="count" class="ng-valid ng-dirty">
<h1 class="ng-binding">Outer <div ng-transclude="">
<h3 class="ng-scope ng-binding">Inner </h3>
</div>
</h1>
</body>
The ng-scope class is a useful marker for where Angular is declaring a new scope.
You can see by the markup that the in the working example both the count properties are enclosed in the scope that is attached to body. So, in this case, the directive scope is a child of the body scope (and therefore has access to it).
However, In the example that is not working, the Outer1 property is sitting outside of the scope that the input is in.
The Angular Scope documentation covers this well. The scopes are arranged in a hierarchy with child scopes having access to parent scopes (but not the other way around):
The application can have multiple scopes, because some directives
create new child scopes (refer to directive documentation to see which
directives create new scopes). When new scopes are created, they are
added as children of their parent scope. This creates a tree structure
which parallels the DOM where they're attached
Long story short - as others have said, this is a scope issue. Using the "ng-transclude" directive creates a new scope. When a new scope is created values from the old scope will be accessible in the new scope (hence the first replace) but after that only objects that are shared between the old/new scope will be updated. That is why using an object would work, but using a value will not.
In your case placing the input field inside of the ng-transclude causes this to only edit the value in that scope, not the value in the parent scope (which is where the count for the "test" directive is pulled from).
Incidentally, this can be an issue with repeaters (ng-repeat) as well as other directives. Its best to use a tool such as "Batarang" in order to find issues such as this. It allows you to look at what is in each scope and determine why the screen isn't showing the "correct" data. Hope that helps explain further!
Add ng-change to input , it should work. The problem is that controller into directive doesn't know about count change.
JS
var App = angular.module('App', []);
App.directive('test', function () {
return {
restrict: 'E',
replace: true,
transclude: true,
template: "<h1>Outer {{this.count}} <div ng-transclude></div></h1>",
controller: function ($scope) {
$scope.count = 1;
$scope.onChange = function(count){
$scope.count = count;
}
}
};
});
HTML
<test>
<h3>Inner {{count}}</h3>
<input type="text" ng-model="count" ng-change="onChange(count)">
</test>
Demo Fiddle
The order matters because of the difference between creating a property on the scope versus actually using an object bound to the scope (especially when a transclude creates a new child scopr). Best practice is to use an object on the scope and bind properties to that object when scope issues can come into play with directives and transcludes.
If you change your code to this, it will work as you were expecting and order does not matter. Notice that I am creating a scope object and placing the count as a property on that object.
<test>
<h3>Inner {{data.count}}</h3>
<input type="text" ng-model="data.count"/>
</test>
var App = angular.module('App', []);
App.directive('test', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
template: "<h1>Outer{{data.count}} <div ng-transclude></div></h1>",
controller: function ($scope) {
$scope.data = {};
$scope.data.count = 1;
}
};
});
This is a great tutorial on this subject. Props to EggHead. https://egghead.io/lessons/angularjs-the-dot
It's a scoping issue.
$scope.count = 1; adds the property count to the scope that <test> is in. Let's call it parent scope.
ng-transclude creates a new scope, let's call it child scope. When <h3>Inner {{count}}</h3> is evaluated, the child scope has no property count so it's read from the parent scope.
<input type="text" ng-model="count"> binds the value of the input to the property count in the child scope. As soon as you enter something the property will be created if it's not there yet. From this point on <h3>Inner {{count}}</h3> gets its value from the child scope.
Scopes in angular are simple JavaScript objects and are connected to their parents via prototypes. So before you enter something the child scope looks something like
{
prototype: { // = parent scope
count: 1
}
}
When you change the value to, say, 5, the scope looks something like
{
count: 5,
prototype: { // = parent scope
count: 1
}
}
Because data binding does something like scope.count = 5.
Here's a work around
Change $scope.count to
$scope.helper = {
count: 1
}
and refactor the rest.
Check this video out for an explanation.
It seems that we cannot override this since ngTransclude will use $transclude function directly.
See: https://github.com/angular/angular.js/blob/master/src/ng/directive/ngTransclude.js
and: http://docs.angularjs.org/api/ng.$compile
transcludeFn - A transclude linking function pre-bound to the correct transclusion scope. The scope can be overridden by an optional first argument. This is the same as the $transclude parameter of directive controllers. function([scope], cloneLinkingFn).

Resources