user3318489 user3318489 - 3 months ago 21
AngularJS Question

AngularJS directive as attribute - change array in directive

I have this directive and if I scroll to top than the link function will be invoked - this works fine.
In the link function I will splice 4 entries of the array - but this is no influence of the view - there are still the whole entries of the array shown.
Therefore my question would be what I can do in order to remove the splices arrayentries from the browser view?

(function() {
'use strict';

angular
.module('myProject.common')
.directive('asScrollTop', asScrollTop);

function asScrollTop() {
var directive = {
restrict: 'A',
scope: { chatMessagesOfUser: '=chatMessagesOfUser' },
link: link
};
return directive;

////////////

function link(scope, element, attr) {
console.log(element);
element.on('scroll', function() {
if(element[0].scrollTop <= 0) {
scope.chatMessagesOfUser.splice(1, 4);
}
});
}
}
})();


The usage of the directive is like this:

<div data-as-scroll-top data-chat-messages-of-user="vm.chatMessagesOfUser">
</div>

Answer

When you modify a bound variable from a directive, you need to inform angular it needs to update. You can do this with $apply().

(function() {
'use strict';

angular
    .module('myProject.common')
    .directive('asScrollTop', asScrollTop);

function asScrollTop() {
    var directive = {
        restrict: 'A',
        scope: { chatMessagesOfUser: '=' },
        link: link
    };
    return directive;

    ////////////

    function link(scope, element, attr) {
        console.log(element);
        element.on('scroll', function() {
          if(element[0].scrollTop <= 0) {
              scope.chatMessagesOfUser.splice(1, 4);
              scope.$apply();
          }
        });
      }
    }
})();

Also note that when you assign a directive a scope variable that is 2-way bound, you don't need the variable name after the = if it's the same name.