0

I have the following issue:

In my controller I have something like:

$scope.current = 0;

And I have some directive who is looking like this:

angular.module('myAPP')
    .directive('post', function() {
        return {
            restrict: 'EA',
            replace: true,
            scope: {
                post: '=',
                index: '='
            },

        link: function(scope) {
          //update the $scope.current here
        },
        templateUrl: 'components/blog/post.html'
    };
});

Can someone explain me whats the best way to do this, its possible to update the $scope inside the link function?

Thanks!

2 Answers 2

6

Your directive has an isolate scope.

To change current from directive, you have to bind it with directive scope variable like this

Like this

html

<post index="current"></post>

js

link: function(scope) {
   scope.index=2;
},
Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct way to do this. See the scope section under docs.angularjs.org/api/ng/service/$compile on how this bidirection = binding works
1

You need to use event handlers. It should look like this:

angular.module('myAPP')
    .directive('post', function() {
        return {
            restrict: 'EA',
            replace: true,
            scope: {
                post: '=',
                index: '='
            },

        link: function(scope) {
          $scope.on('my-event', function(value){
             $scope.current = value;
          });
          //update the $scope.current here
        },
        templateUrl: 'components/play/questions/simple-question.html'
    };
});

And in your controller you will send notification event to your directive:

$scope.emit('my-event', $scope.current);

If your directive lies outside of your controller, than you need to use $rootScope instead.

1 Comment

I am glad I could help:)

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.