Omital Omital - 1 year ago 41
Javascript Question

Why date loaded in link function nit binded to created html in directive?

I want to write directive for repetitive code for example in this sample I want load data from attachmentUsageService and then create html. for first step service load data successfully but this data is not bind to created html element.
Suppose below code for directive

app.directive('mySharedScope', ["", function (attachmentUsageService) {
return {
restrict: 'AE',
template: ' <button ng-click="open()">Test {{attachments.length}}</button><div>',
scope: { },
link: function ($scope, $element, $attrs) {

var attachments = [];

$ = function () {

var _objectType = 0;
var _objectId = $attrs.objectId;

if ($attrs.objectType == 'person')
_objectType = 1;
if ($attrs.objectType == 'company')
_objectType = 2;

attachmentUsageService.getObjectAttachments({ objectId: _objectId, objectType: _objectType, itemCount: 10 }).success(function (data) {
attachments= data.attachments;

why button's text is not for example "Test [number]" after click on it?

Answer Source

attachments is a local Variable, so its not available to your view. Change var attachments = [] to $scope.attachments = [], it should be available in your view.