angular unit testing a $watch on an $attr - javascript

From my understanding $attr.$observe fires once. So there are times to use $watch on an attribute. I am looking to unit test a directive that requires ngModel
scope.$watch(attr.ngModel, function (newValue) {
minlength = parseInt(attr.minLength);
scope.minLengthValidator(newValue);
});
Since this is using scope in the Link function it seems like I could call $digest.
My mocked attribute starts like so...
html = angular.element("<input ng-model=\"myUnit\" min-length=\"3\">");
I am not sure if I can just redefine element.attr('min-length') inside of my spec and run a $digest or if there is a more complex approach since the the watch is passing a new value.
the rest of my mock set up is like so
$rootScope = $rootScope.$new();
element = $compile(html)($rootScope);
$rootScope.$digest(element);
controller = element.controller('ngModel');
scope = element.scope();
I have not tested a $watch on a attribute before so any direction that points me towards solving this would be much appreciated.

scope.$watch(attr.ngModel, ...) will create a watcher on myUnit scope property. Once the watcher is created, it isn't bound to ngModel attribute value.
It can be tested as any other scope watcher:
scope.myUnit = ...;
$rootScope.$digest();
expect(scope.minLengthValidator).toHaveBeenCalledWith(...);
From my understanding $attr.$observe fires once.
No, $attrs.$observe observer will fire on each attribute change, it is preferable to $scope.$watch. As the manual states,
Use $observe to observe the value changes of attributes that contain
interpolation (e.g. src="{{bar}}"). Not only is this very efficient
but it's also the only way to easily get the actual value because
during the linking phase the interpolation hasn't been evaluated yet
and so the value is at this time set to undefined.
The problem is that attributes belong to DOM and can't be tested cleanly. For controller specs $attrs local dependency can be mocked, but it isn't possible in directive specs. For testability reasons it is preferable to bind attributes to scope properties and test the scope only with no $attrs involved.

Related

When exactly is ng-checked called

While using AngularMaterial, I have ng-checked like this:
<md-list>
<md-list-item ng-repeat="option in options">
<p> {{ option }} </p>
<md-checkbox class="md-secondary" aria-label="{{$index}}" ng-checked="exists($index)" ng-click="toggle($index)"></md-checkbox>
</md-list-item>
</md-list>
And my exists function:
$scope.exists = function (optionNum) {
console.log('Inside $scope.exists. option: '+optionNum);
};
My timer:
function updateTimer() {
var onTimeout = function(){
mytimeout = $timeout(onTimeout,1000);
}
var mytimeout = $timeout(onTimeout,1000);
}
With this, the $scope.exists function is getting called every second. Can someone please explain how ng-checked and $timeout related ? and how to avoid this ?
Reason in one word is: digest cycle. Since your function is bound to the view, every time digest cycle happens those expressions gets evaluated as a part of dirty check to make sure if respective DOM needs to be updated or not. This is nothing to do with angular material alone, it is the core angular implementation. Now in your case you are calling $timeout infinitely which means after each timeout execution digest cycle happens to perform dirty check.
Now what you have is fine, but whenever you bind a function to DOM (as a part of view binding, interpolation or property state attributes or even DOM filters - of course events are fine) you should be aware of the fact that you do not perform extensive operation in that function accidentally or intentionally as the app grows, it will slow down the entire app, and will be hard to refactor and diagnose when the app grows larger and problems starts happening. As much as possible bind to a property instead of a function. Note that even if you bind a property still angular $parse creates a getter on it and adds it to the $$watchers queue to be dirty checked every digest cycle, but difference is that it is a simple getter function.
So basically for instance in your case you could bind ng-checked to property
..ng-checked="doesExist"
and set the property doesExist whenever it needs to be updated. So with this instead of checking for the existence every time, you explicitly set the respective property when a respective event happens. That makes the logic explicit as well.
ng-checked, like many of angular's directives are based on watches. Anytime a digest cycle is called, it evaluates all of the watchers (which the function you are using is one of). So every time $timeout evaluates it is starting a new $digest cycle and evaluating all of the watchers. This is part of the "magic" that keeps the view updated with all of the data in your controllers and directives.
Watchers can become a performance issue if you make your functions complex, or make TONS of watchers. It is generally best to have simple logic that returns true or false very quickly and to avoid setting watches on everything.

$watch vs. ngChange

Say that you want to do something when a property of $scope changes. And say that this property is bound to an input field. What are the advantages/disadvantages of using $watch vs. using ngChange?
html
<input ng-model="foo" ng-change="increment()">
<p>foo: {{foo}}</p>
<!-- I want to do something when foo changes.
In this case keep track of the number of changes. -->
<p>fooChangeCount: {{fooChangeCount}}</p>
js
// Option 1: $watch
$scope.$watch('foo', function() {
$scope.fooChangeCount++;
});
// Option 2: ngChange
$scope.fooChangeCount = 0;
$scope.increment = function() {
$scope.fooChangeCount++;
};
http://plnkr.co/edit/4xJWpU6AN9HIp0OSZjgm?p=preview
I understand that there are times when you need to use $watch (if the value you're looking to watch isn't bound to an input field). And I understand that there are times when you need to use ngChange (when you want to do something in response to a change in an input, but not necessarily in response to a scope property change).
However, in this case both accomplish the same thing.
My thoughts:
ngChange seems cleaner, and easier to understand what's happening.
$watch seems like it might be slightly faster, but probably negligible. With ngChange, I think Angular would have to do some extra work in the compile phase to set up the event listeners, and perhaps extra event listeners decrease speed a bit. Regardless of whether or not you use ngChange, the digest cycle runs on changes, so you have an opportunity to listen for something and call a function in response to changes.
Bottom line - You can achieve with $watch every thing you can achieve with ng-change but not vice-versa.
Purposes:
ngChange - binded to a HTML element
$watch - observing scope's model objects (HTML object models included)
My rule of thumb - if you can use ng-change use it to match your scenario, otherwise use $watch
Why you shouldnt use $watch?
It’s inefficient - Adding complexity to your $digest
It’s hard to test effectively
It's not clean
You have it mostly right. ng-change is very DOM specific and for evaluating an expression when the change event fires on a DOM element.
$watch however, is a lower-level (and more general purpose) utility that watches your view model or $scope. So your watch function will fire every time the user types a key (in the example of an input).
So to contrast, one listens to DOM events, the other watches your data.
$watch adds more complexity do the $digest, making it less efficient. In your case ngChange it's a cleaner and easier solution...
Font: http://www.benlesh.com/2013/10/title.html

Angular: $observe an element's text

I already know that you can use attr.$observe within a directive to watch the attributes if they change.
Is there an equivalent to watch the text within an element?
<div my-directive ng-bind="myText || 'Watch me!!!'">Watch me!!!</div>
In the above example, I'd want to watch the text "Watch me!!!". I'd much prefer to do this rather than $watch what is being bound to the directive because of scoping issues.
Watching the DOM for changes is EXPENSIVE, also there is no built in way within Angular to do so. Watching the scope for changes is the correct way to do this.
If you are having issues with scoping then perhaps, with more I formation,that is something we could help with as well.
It's possible to watch DOM changes, here's an example:
http://jsfiddle.net/kihu/t7zr71ma/5/
The trick is to pass a function returning anything you want to watch, e.g.:
scope.$watch(function () {
return element.text();
}, handleChange)
But I think #Enzey is right, you should avoid watching the DOM, instead you should bind data from angular scope and watch it.

Data binding in directive isolated scope

I want to create a directive with isolated scope, but I'm not able to get it working.
jsFiddle
I want to isolate age model in a directive scope. I want to perform some business logic on that model and then set that model to parent binding. I hope the fiddle is explanatory.
I am also adding a button to the template which when clicked should invoke a submit function:
<button ng-click="submit()">click me</button>
It seems the button is working fine, but why is $scope.$watch() is not begin triggered? In a normal situation, if I change the view value it will automatically update the model value. But now it isn't.
$watch requires a dollar sign, and you pass either a function or a string that is evaluated on your scope, i.e.:
$scope.$watch('age', function(value) {
There are many more errors in your code, for instance you don't have a declared variable called 'age' so this line will reference window.age and give you an error because it is undefined, you need to say $scope.age I think:
age = age+10;
It just looks like your updated fiddle is a playground, hope these point you in the right direction. I'd recommend going through the egghead.io angular videos.

Angular multiple instances of same directive, scope is not isolated

I have a problem when creating multiple directives with isolated scope: when I change something in 1st directive it also makes changes in all other directives.
Here is a working example: http://plnkr.co/edit/drBghqHHx2qz20fT91mi?p=preview
(try to add more of Type1 'Available notifications' - a change in 1st will reflect in all other directives of Type1)
I found some solutions to similar problems here but they don't work in my case. Also found a working solution with mapping 'subscription' data to local scope variables in directive (app.js, line 76) but I think there should be a more general way to do this right?
In your directive 'notificationitem' you have the following code, keep it in mind as i explan:
// if all variables are mapped in this way than works
//$scope.enabled = $scope.subscription.enabled;
The reason why all of the 'isolated' scopes are updating is because of this code in your scope declaration in the same directive (notificationitem):
scope: {
subscription: '=',
index: '#'
},
The equal sign on subscription is angular's way of saying "Whenever the current scope updates, go to the parent and update that value as well." This means whenever you update your 'isolated' scope, it updates the parent scope as well. Since all of these isolated scopes are binding to the parent, they will change as well.
Since you want the subscription.value to be the default value of that text field, you will need to do exactly what your commented code is doing:
scope.value = scope.subscription.value;
This will create an isolated value inside of the isolated scope. When scope.value changes, scope.subscription.value will not. All of the text fields now have their own 'value' to keep track of.
Check out this article for information on directive bindings: http://www.ng-newsletter.com/posts/directives.html
Also, another way to get the default value would be to inject your service into the directive, if you don't like the above solution. Hope this all helps.

Categories