2

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.

1
  • Why don't you just initialize it in your controller as you are using 2-way binding ?
    – tomaoq
    CommentedNov 20, 2014 at 13:33

3 Answers 3

3

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

2
  • Man you are the best :). Save me a lot of researching :).CommentedNov 20, 2014 at 13:34
  • 1
    No problem. You only need to use $apply when you are doing outside of angular's context. This is not one of those times.
    – Brocco
    CommentedNov 20, 2014 at 13:39
1

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 = []; } }}); 
    1

    The shortest way:

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

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.