tjm1706 tjm1706 - 2 months ago 7
AngularJS Question

AngularJS :wait in 'link' of directive is not working

In the below source, the watch method in the link part of a custom directive is not working. I use 'link' within the directive because I have to update the DOM structure.

How can I get the watch in the link{} of the directive working EACH time the button is pushed?

EDIT: I found the wrong code. See below 'ERROR' and 'CORRECT' code.

The HTML above this script is (click on a button to increment a variable):

<div ng-controller="AppController as vmx">
<button ng-click="vmx.incrementFoo()">Increment Foo</button>:
{{ vmx.fooCount }}.
<div foo-count-updated></div>
</div>


Angular code:

angular.module( "myapp", [])
.controller( "AppController", myAppController)
.directive('showAlsoInCustomDirective', showAlsoInCustomDirective);

// *** CONTROLLER
function myAppController( $scope ) {
var vm = this;
vm.fooCount = 0;
vm.copiedFooCount = 0;

// ERROR code:
// **vm.getFooCount** = function() {
// return vm.fooCount;
// }

// CORRECT code:
getFooCount = function() {
return vm.fooCount;
}
vm.getFooCount = getFooCount;

vm.incrementFoo = incrementFoo;
function incrementFoo() {
++vm.fooCount;
}
}

// *** DIRECTIVE
.directive('fooCountUpdated', fooCountUpdater);
function fooCountUpdater() {
var indirectivecounter = 0;
getFooCountInDirective = function() {
return getFooCount();
}
var watcherFn = function (watchScope) {
return getFooCountInDirective();
}
return {
link: function (scope, element, attrs) {
scope.$watch(watcherFn, function (newValue, oldValue) {
element.html( "Got the change: " + newValue);
})
}};
}


The complete source is put in this file:
https://plnkr.co/edit/J6nfLQ3dmLW0gDNXV0J5?p=preview

Answer

As indicated above, the solution was simple. It is also in the plunker file.

HTML:

<div ng-controller="AppController as vmx">
    <button ng-click="vmx.incrementFoo()">Increment Foo</button>:
    {{ vmx.fooCount }}.
    <div foo-count-updated></div>
</div>

Angular code:

angular.module( "myapp", [])
.controller( "AppController", function( $scope ) {
    var vm = this;
    vm.fooCount = 0;
    getFooCount = function() { 
        return vm.fooCount;
    }
    vm.getFooCount = getFooCount;
    vm.incrementFoo = incrementFoo;
    function incrementFoo() {
        ++vm.fooCount;
    }
})
.directive('fooCountUpdated', fooCountUpdater);
function fooCountUpdater() {
    var indirectivecounter = 0; 
    getFooCountInDirective = function() { 
        return getFooCount();
    }
    var watcherFn = function (watchScope) {
        return getFooCountInDirective();
    }
    return { 
        link: function (scope, element, attrs) {
            scope.$watch(watcherFn, function (newValue, oldValue) {
            element.html( "Got the change: " + newValue);
         })
    }};
 }