Pacuraru Daniel
Pacuraru Daniel

Reputation: 1205

angular call controller function inside directive

i am working on a mini contacts list and i am trying ot achieve a drag and drop effect. Right now i have a controller that brings me data from a DB and looks like this.

Index.controller('cIndex', function($scope, $http) {
    $scope.init = function() {
        $http.get('php/contacts.php').success(function(data) {
            $scope.jsonContactsList = data;
            $scope.jsonContactsDetail = [];
        });
    };
    $scope.init();

    $scope.listdetail = function(index) {
        alert(index);
    };
});

And this controller adds a list of contacts on the screen. I want to make that when i drag an item from the list and drop it outside the list, the item disapears from the list and appears as a detailed div about that specific contact.

Now i have 2 directives, 1 that makes the drag effect and 1 that makes the drop effect and they look like this.

Index.directive('contactListDrag', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attr) {
            var options = scope.$eval(attr.contactListDrag);
            elem.draggable(options);
        }
    };
});

Index.directive('contactListDrop', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attr) {
            elem.droppable({accept: '.contact-list-item'});
            elem.bind('drop', function(event, ui) {
                var id = parseInt($(ui.draggable).attr('id'), 10);
                $scope.listdetail(id);
            });
        }
    };
});

Now inside the controller i have a function called listdetail, which i intend to make it change a line inside the jsonContactsList into jsonContactsDetail, but in order to do that, i need to call the listdetail function from the controller, inside the droppable contactListDrop directive.

Thank you in advance, Daniel!

Upvotes: 1

Views: 1870

Answers (2)

m.e.conroy
m.e.conroy

Reputation: 3538

$scope is not available inside your directive. You need to tell your directive about its parent. Look at the section on Understanding Transclusion and Scope in the Angular docs here: http://docs.angularjs.org/guide/directive

scope: {
    var: '='
}

You could also scope.$emit an event from your directive and listen for it in the controller by using $scope.$on - I think this is the better solution since your directive wouldn't be tied to a controller having a certain function.

Upvotes: 0

Pacuraru Daniel
Pacuraru Daniel

Reputation: 1205

I found out the fix on this, i had to use scope.listdetail(id); without the dollar sign.

Upvotes: 2

Related Questions