user3318489 user3318489 - 3 months ago 7
AngularJS Question

AngularJS directive as attribute - make array available in directive

I have this html fragment with my directive asScrollTop as attribute:

<div data-as-scroll-top>
<div data-ng-repeat="chatMessageOfUser in vm.chatMessagesOfUser">
<!-- use chatMessageOfUser -->
</div>
</div>


and this is my directive:

(function() {
'use strict';

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

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

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

function link(scope, element, attr) {
console.log(element);
element.on('scroll', function() {
if(element[0].scrollTop <= 0) {
// here I need vm.chatMessagesOfUser or the first entry of the
// vm.chatMessagesOfUser array
}
});
}
}
})();


My question now would be how I can make the the vm.chatMessagesOfUser array available in directive?

Answer

You can defined scope in directive like

var directive = {
        restrict: 'A',
        scope: { yourList: '=yourList' },
        link: link
    };
    return directive;

function link(scope, element, attr) {
    console.log(scope.yourList);
    };

and set value in html markup

<div data-as-scroll-top your-list="vm.chatMessagesOfUser"></div>