Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

share|improve this question
    
Why don't you just initialize it in your controller as you are using 2-way binding ? – tiledcode Nov 20 '14 at 13:33
up vote 3 down vote accepted

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

share|improve this answer
    
Man you are the best :). Save me a lot of researching :). – Georgi Naumov Nov 20 '14 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 Nov 20 '14 at 13:39

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

            }
 }});
share|improve this answer

The shortest way:

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.