Custom directive with watcher only fires once. Does not watch - angularjs

I'm attempting to fire an animation using a custom directive, "activate" which I use as an attribute here, partials/test.html
<div activate="{{cardTapped}}" >
I define the directive following my app definition in js/app.js
myApp.directive('activate', function ($animate) {
return function(scope, element, attrs) {
scope.$watch(attrs.activate,function(newValue){
console.log('fire');
if(newValue){
$animate.addClass(element, "full");
}
else{
$animate.removeClass(element, "full");
}
},true);
};
});
However, $watch is only firing on page load. When cardTapped changes values, nothing registers. I've tried several variations of parameters here to no avail and I've seen a dozen questions similar to this but so far I havent found a solution
Any thoughts?

The problem is that you wrote it like this: activate="{{cardTapped}}" while it should be activate="cardTapped".
When you want to use a watcher, let it watch a variable, not a string.
JS Fiddle

Related

When does Angulars link function run?

From what I understand it only runs once before the page is rendered. But is there ever a case where it runs after the page has been rendered?
I tried testing a few things with this plnkr:
angular
.module('app', [])
.directive('test', function($http) {
return {
restrict: 'E',
template: '<input />',
link: function(scope, el, attrs) {
var input = angular.element(el[0].children[0]);
input.on('change', function() {
console.log('change event');
scope.$apply(function() {
console.log('digest cycle');
});
});
input.on('keyup', function() {
console.log('keyup event');
var root = 'http://jsonplaceholder.typicode.com';
$http.get(root+'/users')
.success(function() {
console.log('http request successful');
})
.error(function() {
console.log('http request error');
});
});
console.log('link function run');
}
};
});
Does typing in the input field cause the link function to run?
Do event listeners cause the link function to run?
Do http requests (made with $http?) cause the link function to run?
Do digest cycles cause the link function to run?
The answer to all of these questions seem to be "no".
The link function runs when an instance of the directive is compiled, in this case, when a <test></test> element is created. That can be when angular's bootstrapping compiles the page, when it comes into being from a ng-if, when a ng-repeat makes it, when it's made with $compile, etc.
link will never fire twice for the same instance of the directive. Notably, it fires right after the template has been compiled in the directive's lifecycle.
1 - No, it causes to change the only ng-model if you have it binded.
2 - No, it will only launch the code inside the event binds.
3 - Again no, the event bind will launch the $http.get(). And please don't put an $http directly on your directive. Use a factory or something like that.
4 - Dunno
As Dylan Watt said, the directive link runs only when the directive is compiled (only once) per element/attr.... You can compile it in different ways. Plain http, $compile, ng-repeat....
You can create a $watch inside your directive to "relaunch" some code on a binded element change.
This maybe can help you: How to call a method defined in an AngularJS directive?

AngularJS: accessing the ngTouch service from a directive?

I really love how the new ng-click directive in Angular now automatically includes functionality for touch events. However, I am wondering if it is possible to access that touch-event service from my custom directive? I have lots of directives that require that I bind a click event to the given element, but I'm simply doing that using the typical jquery syntax (ex: element.on('click', function(){ ... })). Is there a way that I can bind an ng-click event to an element within a directive? Without having to manually put a ng-click tag on my element in the HTML of my view...?
I want to be able to harness the power of both click and touch events. I could obviously import a library (such as HammerJS or QuoJS) but I would prefer not to have to do that, especially since Angular is already doing it.
I can access the $swipe service and bind different elements to that, but is there a similar service for ngTouch?
For reference, this is an example of when I would want to do this:
mod.directive('datepicker', ['$timeout', function($timeout){
return {
link: function(scope, elem, attrs){
var picker = new DatePicker();
elem.on('click', function(e){
picker.show();
});
// I would rather do something like:
// elem.on('ngTouch', function(){ ... });
//
// or even:
// $ngTouch.bind(elem, {'click': ..., 'touch': ...});
}
}
}]);
UPDATE: As noted by below, the source code for the ng-click directive is here. Can anyone see a way to harness that code and turn it into a "bindable" service?
I don't think that's quite the right approach. I'd approach this by using a template within your directive and then using ngTouch within that.
mod.directive('datepicker', ['$timeout', function ($timeout) {
return {
template: '<div ng-touch="doSomethingUseful()"></div>',
link: function (scope, elem, attrs) {
var picker = new DatePicker();
scope.doSomethingUseful = function () {
// Your code.
}
}
}
}]);
UPDATE
Full example with additional attributes on the directive element:
http://codepen.io/ed_conolly/pen/qJDcr

Adding ng-change to child elements from linking function of directive

I created a directive that should add a ng-change directive dynamically to all child input tags:
myApp.directive('autosave', function ($compile) {
return {
compile: function compile(tElement, tAttrs) {
return function postLink(scope, iElement, iAttrs) {
var shouldRun = scope.$eval(iAttrs.autosave);
if (shouldRun) {
iElement.find(':input[ng-model]').each(function () {
$(this).attr("ng-change", iAttrs.ngSubmit);
});
$compile(iElement.contents())(scope);
console.log("Done");
}
}; //end linking fn
}
};
});
The problem that I have is that the ng-change directive isn't running. I can see it that its added to the DOM element BUT not executing when value changes.
The strange thing is that if I try with ng-click, it does work.
Dont know if this is a bug on ng-change or if I did somehting wrong.
Fiddle is with ng-click (click on the input) http://jsfiddle.net/dimirc/fq52V/
Fiddle is with ng-change (should fire on change) http://jsfiddle.net/dimirc/6E3Sk/
BTW, I can make this work if I move all to compile function, but I need to be able to evaluate the attribute of the directive and I dont have access to directive from compile fn.
Thanks
You make your life harder than it is. you do'nt need to do all the angular compile/eval/etc stuff - at the end angular is javascript : see your modified (and now working) example here :
if (shouldRun) {
iElement.find(':input[ng-model]').on( 'change', function () {
this.form.submit();
});
console.log("Done");
}
http://jsfiddle.net/lgersman/WuW8B/1/
a few notes to your approach :
ng-change maps directly to the javascript change event. so your submit handler will never be called if somebody uses cut/copy/paste on the INPUT elements. the better solution would be to use the "input" event (which catches all modification cases).
native events like change/input etc will be bubbled up to the parent dom elements in the browser. so it would have exactly the same to attach the change listener to the form instead of each input.
if you want to autosave EVERY edit that you will have an unbelievable mass of calls to your submit handler. a better approach would be to slow-down/throttle the submit event delegation (see http://orangevolt.blogspot.de/2013/08/debounced-throttled-model-updates-for.html ).
if you want to autosave EVERY edit you skip your change handler stuff completely and suimply watch the scope for changes (which will happen during angular model updates caused by edits) and everything will be fine :
scope.watch( function() {
eElement[0].submit();
});

How to trigger ng-change in directive test in AngularJS

I have the following AngularJS directive that creates an input element. Input has ng-change attribute that runs doIt() function. In my directive's unit test I want to check if doIt function is called when users changes the input. But the test does not pass. Though it works in the browser when testing manually.
Directive:
...
template: "<input ng-model='myModel' ng-change='doIt()' type='text'>"
Test:
el.find('input').trigger('change') // Dos not trigger ng-change
Live demo (ng-change): http://plnkr.co/edit/0yaUP6IQk7EIneRmphbW?p=preview
Now, the test passes if I manually bind change event instead of using ng-change attribute.
template: "<input ng-model='myModel' type='text'>",
link: function(scope, element, attrs) {
element.bind('change', function(event) {
scope.doIt();
});
}
Live demo (manual binding): http://plnkr.co/edit/dizuRaTFn4Ay1t41jL1K?p=preview
Is there a way to use ng-change and make it testable? Thank you.
From your explanatory comment:
All I want to do in directive's test is to check that doIt is called when user changes the input.
Whether or not the expression indicated by ng-change is correctly evaluated or not is really the responsibility of the ngModel directive, so I'm not sure I'd test it in this way; instead, I'd trust that the ngModel and ngChange directives have been correctly implemented and tested to call the function specified, and just test that calling the function itself affects the directive in the correct manner. An end-to-end or integration test could be used to handle the full-use scenario.
That said, you can get hold of the ngModelController instance that drives the ngModel change callback and set the view value yourself:
it('trigger doIt', function() {
var ngModelController = el.find('input').controller('ngModel');
ngModelController.$setViewValue('test');
expect($scope.youDidIt).toBe(true);
});
As I said, though, I feel like this is reaching too far into ngModel's responsibilities, breaking the black-boxing you get with naturally composable directives.
Example: http://plnkr.co/edit/BaWpxLuMh3HvivPUbrsd?p=preview
[Update]
After looking around at the AngularJS source, I found that the following also works:
it('trigger doIt', function() {
el.find('input').trigger('input');
expect($scope.youDidIt).toBe(true);
});
It looks like the event is different in some browsers; input seems to work for Chrome.
Example: http://plnkr.co/edit/rbZ5OnBtKMzdpmPkmn2B?p=preview
Here is the relevant AngularJS code, which uses the $sniffer service to figure out which event to trigger:
changeInputValueTo = function(value) {
inputElm.val(value);
browserTrigger(inputElm, $sniffer.hasEvent('input') ? 'input' : 'change');
};
Even having this, I'm not sure I'd test a directive in this way.
I googled "angular directive trigger ng-change" and this StackOverflow question was the closest I got to anything useful, so I'll answer "How to trigger ng-change in a directive", since others are bound to land on this page, and I don't know how else to provide this information.
Inside the link function on the directive, this will trigger the ng-change function on your element:
element.controller('ngModel').$viewChangeListeners[0]();
element.trigger("change") and element.trigger("input") did not work for me, neither did anything else I could find online.
As an example, triggering the ng-change on blur:
wpModule.directive('triggerChangeOnBlur', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('blur', function () {
element.controller('ngModel').$viewChangeListeners[0]();
});
}
};
}]);
I'm sorry that this is not directly answering OP's question. I will be more than happy to take some sound advice on where and how to share this information.
simple and it works
in your unit test env:
spyOn(self, 'updateTransactionPrice');
var el = compile('<form name="form" latest novalidate json-schema="main.schema_discount" json-schema-model="main._data"><input type="text" ng-model="main._data.reverse_discount" ng-class="{ \'form-invalid\': form.reverse_discount.$invalid }" ng-change="main.transactionPrice(form);" name="reverse_discount" class="form-control-basic" placeholder="" ng-disabled="!main.selectedProduct.total_price"></form>')(scope);
el.find('input').triggerHandler('change');
expect(self.updateTransactionPrice).toHaveBeenCalled();
I was looking for this simple line for long hours.
Just to save that in here.
How to select value from html-select, using Karma, and so get ng-change function working?
HTML:
Controller or directive JS:
$scope.itemTypes = [{name: 'Some name 1', value: 'value_1'}, {name: 'Some name 2', value: 'value_2'}]
$scope.itemTypeSelected = function () {
console.log("Yesssa !!!!");
};
Karma test fragment:
angular.element(element.find("#selectedItemType")[0]).val('value_1').change();
console.log("selected model.selectedItemType", element.isolateScope().model.selectedItemType);
Console:
'Yesssa !!!!'
'selected model.selectedItemType', 'value_1'
Have been trying to get this to work, but failed on every attempt. Finally concluded that my ng-model-options with a debounce setting on the onUpdate, was the problem.
If you have a debounce, make sure that you flush with the $timeout service. In angular mock, this timeout service has been extended with a flush operation, which handles all unfulfilled requests/actions.
var tobetriggered = angular.element(element[0].querySelector('.js-triggervalue'));
tobetriggered.val('value');
tobetriggered.trigger('change');
$timeout.flush();

Fire an event immediately after $scope.$digest

In my AngularJS app, there's several points at which I want to wait for a $scope to be processed into the DOM, and then run some code on it, like a jQuery fadeIn, for example.
Is there a way to listen for a "digestComplete" message of some sort?
My current method is: immediately after setting whatever $scope variables I want rendered, use setTimeout with a delay of 0 ms, so that it will let the scope finish digesting, and then run the code, which works perfectly. Only problem is, I very occasionally see the DOM render before that setTimeout returns. I'd like a method that is guaranteed to fire after digest, and before render.
In this jQuery fade-in-and-out fiddle (which I found it on the JSFiddles Examples wiki page), the author defines a "fadey" directive and performs the jQuery fadeIn (or fadeOut) in the directive's link function"
<li ng-repeat="item in items" fadey="500">
...
myApp.directive('fadey', function() {
return {
restrict: 'A',
link: function(scope, elm, attrs) {
var duration = parseInt(attrs.fadey);
if (isNaN(duration)) {
duration = 500;
}
elm = jQuery(elm); // this line is not needed if jQuery is loaded before Angular
elm.hide();
elm.fadeIn(duration)
Another possible solution is to use $evalAsync: see this comment by Miško, in which he states:
The asyncEval is after the DOM construction but before the browser renders.
I believe that is the time you want to attach the jquery plugins. otherwise
you will have flicker. if you really want to do after the browser render
you can do $defer(fn, 0);
($defer was renamed $timeout).
However, I think using a directive (since you are manipulating the DOM) is the better approach.
Here's a SO post where the OP tried listening for $viewContentLoaded events on the scope (which is yet another alternative), in order to apply some jQuery functions. The suggestion/answer was again to use a directive.
Alternatively, this example will work the same way as an AngularJS built-in ng-show directive, except it will fade-in or fade-out based on AngularJS condition:
<li ng-repeat="item in items" ng-ds-fade="{condition}">
<!-- E.g.: ng-ds-fade="items.length > 0" -->
...
myApp.directive('ngDsFade', function () {
return function(scope, element, attrs) {
element.css('display', 'none');
scope.$watch(attrs.ngDsFade, function(value) {
if (value) {
element.fadeIn(200);
} else {
element.fadeOut(100);
}
});
};
});
Source:
http://www.codeproject.com/Articles/464939/Angular-JS-Using-Directives-to-Create-Custom-Attri
If all you want is to run some jQuery stuff why not try the Angular-UI jQuery Passthrough?

Resources