Georgi Naumov
Georgi Naumov

Reputation: 4201

AngularJS directive create empty array in scope.

I have created one directive and use scope variables in this way:

<div data-create-instants-since-beginning data-daysnum="daysnum" data-tostore="tostore">

I want when tostore is undefined to set it to empty array but unfortunately this not working.

.directive("createInstantsSinceBeginning", function () {
        return {
            scope: {
                daysnum: "=",
                tostore: "="
            },
            link: function ($scope, element) {
                if (typeof $scope.tostore == 'undefined') {
                    $scope.$apply(function () {
                        $scope.tostore = [];
                    });
                }
    // other code .. 

How I can solve the problem?

Best regards.

Upvotes: 2

Views: 9461

Answers (3)

Antonio
Antonio

Reputation: 901

The shortest way:

.directive("createInstantsSinceBeginning", function () {
    return {
        scope: {
            daysnum: "=",
            tostore: "="
        },
        link: function ($scope, element) {
            $scope.tostore = $scope.tostore || [];
        }
// other code .. 

Upvotes: 1

Michael
Michael

Reputation: 3326

Just do it in the directive's controller:

app.directive('createInstantsSinceBeginning',function(){
        return {
            scope: {
                daysnum: "=",
                tostore: "="
            },
            controller: function($scope){
                if (  $scope.tostore === undefined ) 
                    $scope.tostore = [];

            }
 }});

Upvotes: 1

Brocco
Brocco

Reputation: 64853

Try taking out the $scope.apply

.directive("createInstantsSinceBeginning", function() {
  return {
    scope: {
      daysnum: "=",
      tostore: "="
    },
    link: function(scope, element) {
      if (typeof scope.tostore == 'undefined') {
        scope.tostore = [];
      }
    }
  };
});

See working example: http://plnkr.co/edit/OVsKcDebdNhxgCfdig4q?p=preview

Upvotes: 3

Related Questions