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 ? Commented Nov 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

Sign up to request clarification or add additional context in comments.

2 Comments

Man you are the best :). Save me a lot of researching :).
No problem. You only need to use $apply when you are doing outside of angular's context. This is not one of those times.
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 = [];

            }
 }});

Comments

1

The shortest way:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.