AngularJS : ng-if | Hidden(Removed) ng-model variable not removed from $scope - angularjs

I am trying to understand the working of ng-if in contrast with ng-show.
After reading the docs and going through the related stackoverflow question here, I understand that ng-if removes the DOM element and the scope variables inside that ng-if are removed.i.e ng-model variables inside the 'removed' ng-if element wont appear in $scope.
From the Angular ng-if docs:-
Note that when an element is removed using ngIf its scope is destroyed
and a new scope is created when the element is restored. The scope
created within ngIf inherits from its parent scope using prototypal
inheritance. An important implication of this is if ngModel is used
within ngIf to bind to a javascript primitive defined in the parent
scope.
Consider following code snippet:-
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.10/angular.min.js"></script>
</head>
<body data-ng-app="myModule">
<div data-ng-controller="TestController">
<input name="first" type="number" data-ng-model="form.x" placeholder="Enter Number X"/>
<input name="second" type="number" data-ng-if="form.x>5" data-ng-model="form.y" placeholder="Enter Number Y"/>
<input type="button" value="Click" ng-click="save()"/>
</div>
<script type="text/javascript">
var myModule = angular.module("myModule",[]);
myModule.controller("TestController",function($scope){
$scope.form = {};
$scope.form.x = 0;
$scope.form.y = 0;
$scope.save = function(){
console.log($scope.form);
};
});
</script>
</html>
This is pretty simple use case - show the second number input field only when first is greater than 5.
The save button click delegates to 'save' function in the controller which simply prints out the 'form' object of $scope.
Problem:-
Input 1:-
Enter x=6 and y=2
Output 1 : {x: 6, y: 2}
Input 2:-
Enter x=3
Output 2 : {x: 3, y: 2}
I am not able to understand why 'output 2' still shows y =2. If its DOM has been removed, shouldn't the output be just {x:3} ?
What should I do if I want to remove (ngIf-removed) model from the scope?
Thanks

Problem
To further what #Chandermani pointed out in comments, ng-if creates a new scope, which has its own variables. It does, however, prototypically inherit from its parent scope, so if you set a property on an existing parent object, such as what you're doing by using form.y, when the child scope is destroyed, that property remains unaffected.
Quick fix solution
You could add another directive to the same element as the one you're setting ng-if on, which deletes the property from the scope on $destroy:
Directive
myModule.directive('destroyY', function(){
return function(scope, elem, attrs) {
scope.$on('$destroy', function(){
if(scope.form.y) delete scope.form.y;
})
}
});
View
<input ... data-ng-if="form.x>5" destroy-y .../>
Demo
Note: I saw that #user2334204 posted something similar. I decided to post this anyway because here the value of x won't have to be checked every digest

Hi there :D you could set a watcher on your "x" variable, something like this:
$scope.$watch(function(){
return $scope.form.x;
},function(){
if($scope.form.x < 5) delete $scope.form.y;
});
Although i don't know if using "delete" is a good practice...
Hope it works for you.
----EDIT----
Another approach:
<input ng-model="form.x" ng-change="check(form.x)">
And in your controller:
$scope.check = function(x){
if(x < 5 ) delete $scope.form.y;
};
Though i think #Marc Kline option is even better.

For dynamic key, you can define a directive like below:
myModule.directive('removeKey', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$on('$destroy', function () {
let attributes = scope.$eval(attrs.removeKey);
if (scope.$parent[attributes.mainModel].hasOwnProperty(attributes.modelKey))
delete scope.$parent[attributes.mainModel][attributes.modelKey];
});
}
};
});
and your view something looks like this:
<div ng-if="condition === 0">
<input ng-model="myFormJson.inputOne" remove-key='{"mainModel":"myFormJson","modelKey":"inputOne"}' />
</div>
<div ng-if="condition === 1">
<input ng-model="myFormJson.inputTwo" remove-key='{"mainModel":"myFormJson","modelKey":"inputTwo"}' />
</div>

Related

Update a scope variable from a directive (angularJS)

I have a directive I would like to apply to multiple input elements to change their value. I've been successful in applying it to the input elements value, but for some reason that is not being reflected in the scope. I'm kinda new to Angular and apologize if I'm missing some kind of obvious answer.
http://jsfiddle.net/hmko75td/ JS Fiddle
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<select ng-model='Factor'>
<option value=1>1</option>
<option value=2>2</option>
<option value=5>5</option>
</select>
<br />
<input convert-input ng-model="myNumber">
{{myNumber}}
<br />
<input convert-input ng-model="myNumber2">
{{myNumber2}}
<br />
<input convert-input ng-model="myNumber3">
{{myNumber3}}
<br />
</div>
</div>
var app = angular.module('myApp',[]);
app.controller('MyCtrl', function($scope) {
$scope.myNumber = 1;
$scope.myNumber2 = 2;
$scope.myNumber3 = 3;
$scope.Factor = 1;
});
app.directive("convertInput", function () {
return {
require: 'ngModel',
restrict: "A",
link: function (scope, element, attrs) {
scope.$watch('Factor', function () {
if(scope.Factor){
element[0].value = scope.Factor * element[0].value;
}
});
}
};
});
This simplified example shows the crux of my problem. When changing the value of the droplist it correctly updates the element's value on the page, but that does not get translated correctly back into the scope variable.
Any ideas how to either 1) tell the directive which scope variable needs to be updated or 2) force the model to update based on the inputs value?
Thanks!
One constraint I see with your snippet is that you need all uses of your convert-input directive to share Factor, which exists in an enclosing parent scope.
In such a case, one viable approach would be to use the attrs passed into the directive to extract the name of the ng-model binding, and then to update the corresponding binding via scope.
scope[attrs.ngModel] *= scope.Factor;
Here's a fork of your JSFiddle demonstrating this:
http://jsfiddle.net/m4hvre2y/
Another approach to having directives update an ng-model in a parent scope would be to declare two-way binding (e.g. scope: { ngModel: '='), but it isn't applicable in your case due to the constraint I mentioned above. If you did this, the isolated scope means you lose access to Factor unless it's specifically passed into the directive.

Directive with ng-model Attribute Not Resolving Using $http

Trying to make a rating directive but I'm stuck at getting rating2 to work. The first rating worked because the rating1 is hardcoded within the controller. But normally I have to get the saved rating from the db, which I'm trying to do with rating2, as u can see the value is fetched but the directive is not appearing.
https://codepen.io/eldyvoon/pen/MbBNLP
<div star-rating ng-model="rating.rating1" max="10" on-rating-select="rating.rateFunction(rating)"></div>
<br>but rating2 is actually there:
{{rating.rating2}}
<star-rating ng-model="rating.rating2" readonly="rating.isReadonly"></star-rating>
Need expert of directive to help.
Initiate rating2 :
function RatingController($http) {
this.rating1 = 5;
this.rating2 = 0; //ADD THIS LINE
var self = this;
it works for me
check here
First of all, I'm not a directive expert but i'm trying to help. I think that when html is first load, the values from db not finish execute and bind into html. The best way is not using directive instead using controller to fetch data from db.
You pass a model without rating2 into your directive and the changes from the parent controller won't affect it, because variable is created afterwards. Adding a watcher in your linker on parent scope will solve the problem;
scope.$parent.$watch('', function(rating){
updateStars();
});
Other solution would be to define a starting value in your controller.
this.rating2 = 1;
Notice that it is bad design to have a scope variable for each rating. It is cleaner to have an array of ratings and you actually do not need the watcher by doing so.
https://codepen.io/hoschnok/pen/LbJPqL
angular controller
function RatingController($http) {
this.ratings = [4];
var self = this;
$http.get('https://api.myjson.com/bins/o0r69').then(function(res){
self.ratings.push(res.data.rating2);
});
}
HTML
<div ng-app="app" ng-controller="RatingController as rating" class="container">
<div ng-repeat="r in rating.ratings">
<div star-rating ng-model="r" max="10" on-rating-select="rating.rateFunction(rating)"></div>
</div>
</div>
The watcher change handler function has parameters reversed:
//INCORRECT parameters
//scope.$watch('ratingValue', function(oldValue, newValue) {
//CORRECT parameters
scope.$watch('ratingValue', function(newValue, oldValue) {
if (newValue) {
updateStars();
}
});
The first argument of the listening function should be newValue.
The DEMO on CodePen
ALSO
The ng- prefix is reserved for core directives. See AngularJS Wiki -- Best Practices
JS
scope: {
//Avoid using ng- prefix
//ratingValue: '=ngModel',
ratingValue: '=myModel',
max: '=?', // optional (default is 5)
onRatingSelect: '&?',
readonly: '=?'
},
HTML
<!-- AVOID using the ng- prefix
<star-rating ng-if='rating' ng-model="rating.rating2"
max="10" on-rating-select="rating.rateFunction(rating)">
</star-rating>
-->
<!-- INSTEAD -->
<star-rating ng-if='rating' my-model="rating.rating2"
max="10" on-rating-select="rating.rateFunction(rating)">
</star-rating>
When a custom directve uses the name ng-model for an attribute, the AngularJS framework instantiates an ngModelController. If the directive doesn't use the services of that controller, it is best not to instantiate it.

Angular: What is a good way to hide undefined attributes that exist in isolated scopes?

I wanted to rewrite this fiddle as it no longer worked in angular 1.2.1. From this exercise, I learned that a template is apparently always needed now in the isolated scopes.
somewhere in the directive:
template: '<p>myAttr1 = {{myAttr1}} // Passed by my-attr1<br>
myAttr2 = {{myAttr2}} // Passed by my-alias-attr2 <br>
myAttr3 = {{myAttr3}} // From controller
</p>',
I was not able,however, to successfully add this to the template:
<p ng-show="myAttr4">myAttr4= {{myAttr4}} // Hidden and missing from attrs</p>
What is a good way to hide undefined attributes that are defined on the isolated scope but not given a value from the dom?
my humble fiddle
EDIT: I use a directive called my-d1 to encapsulate the bootstrap tags. I use my-d2 to demo how to use the # in isolated scopes.
Working version merged with Sly's suggestions
I ran into the same template issue in Angular 1.2.0, see the first entry in the 1.2.0 breaking changes:
Child elements that are defined either in the application template or in some other directives template do not get the isolate scope. In theory, nobody should rely on this behavior, as it is very rare - in most cases the isolate directive has a template.
I'm not exactly sure what the issue is that you are encountering - it might be some incorrect markup or you are misnaming the scope variables listed in your isolate scope.
Using ng-show will correctly hide the element if the attribute has not been passed in.
i.e. your example here is correct: <p ng-show="myAttr4">myAttr4= {{myAttr4}}</p>
Updated version of your Fiddle: http://jsfiddle.net/Sly_cardinal/6paHM/1/
HTML:
<div ng-app='app'>
<div class="dir" my-directive my-attr1="value one" my-attr3='value three'>
</div>
<div class="dir" my-directive my-attr1="value one" my-attr3='value three' my-attr4='value four'>
</div>
</div>
JavaScript:
var app = angular.module('app', []);
app.directive('myDirective', function () {
return {
// can copy from $attrs into scope
scope: {
one: '#myAttr1',
two: '#myAttr2',
three: '#myAttr3'
},
controller: function ($scope, $element, $attrs) {
// can copy from $attrs to controller
$scope.four = $attrs.myAttr4 || 'Fourth value is missing';
},
template: '<p>myAttr1 = {{one}} // Passed by my-attr1</p> '+
'<p ng-show="two">myAttr2 = {{two}} // Passed by my-alias-attr2 </p>'+
'<p>myAttr3 = {{three}} // From controller</p>'+
'<p ng-show="four">myAttr4= {{four}} // Has a value and is shown</p>'
}
});

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).

Checkbox not binding to scope in angularjs

I am trying to bind a checkbox to scope using ng-model. The checkbox's initial state corresponds to the scope model just fine, but when I check/uncheck the checkbox, the model does not change. Some things to note is that the template is dynamically loaded at runtime using ng-include
app.controller "OrdersController", ($scope, $http, $location, $state, $stateParams, Order) ->
$scope.billing_is_shipping = false
$scope.bind_billing_to_shipping = ->
console.log $scope.billing_is_shipping
<input type="checkbox" ng-model="billing_is_shipping"/>
When I check the box the console logs false, when I uncheck the box, the console again logs false. I also have an order model on the scope, and if I change the checkbox's model to be order.billing_is_shipping, it works fine
I struggled with this problem for a while. What worked was to bind the input to an object instead of a primitive.
<!-- Partial -->
<input type="checkbox" ng-model="someObject.someProperty"> Check Me!
// Controller
$scope.someObject.someProperty = false
If the template is loaded using ng-include, you need to use $parent to access the model defined in the parent scope since ng-include if you want to update by clicking on the checkbox.
<div ng-app ng-controller="Ctrl">
<div ng-include src="'template.html'"></div>
</div>
<script type="text/ng-template" id="template.html">
<input type="checkbox" ng-model="$parent.billing_is_shipping" ng-change="checked()"/>
</script>
function Ctrl($scope) {
$scope.billing_is_shipping = true;
$scope.checked = function(){
console.log($scope.billing_is_shipping);
}
}
DEMO
In my directive (in the link function) I had created scope variable success like this:
link: function(scope, element, attrs) {
"use strict";
scope.success = false;
And in the scope template included input tag like:
<input type="checkbox" ng-model="success">
This did not work.
In the end I changed my scope variable to look like this:
link: function(scope, element, attrs) {
"use strict";
scope.outcome = {
success : false
};
And my input tag to look like this:
<input type="checkbox" ng-model="outcome.success">
It now works as expected. I knew an explanation for this, but forgot, maybe someone will fill it in for me. :)
Expanding on Matt's answer, please see this Egghead.io video that addresses this very issue and provides an explanation for: Why binding properties directly to $scope can cause issues
see: https://groups.google.com/forum/#!topic/angular/7Nd_me5YrHU
Usually this is due to another directive in-between your ng-controller
and your input that is creating a new scope. When the select writes
out it value, it will write it up to the most recent scope, so it
would write it to this scope rather than the parent that is further
away.
The best practice is to never bind directly to a variable on the scope
in an ng-model, this is also known as always including a "dot" in
your ngmodel.

Resources