Max Ferguson
Max Ferguson

Reputation: 676

How to call AngularJS JavaScript directive methods from the global scope

I have a directive like the one of the examples from AngularJS, shown below. How can I call the toggle method from the global scope? I want to be able to toggle the zippy from some legacy code.

myApp.directive('zippy', 
function(){
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: { title:'bind' },
        template:
        '<div class="zippy">' +
        '<div class="title">{{title}}</div>' +
        '<div class="body" ng-transclude></div>' +
        '</div>',
        link: function(scope, element, attrs) {
            var title = angular.element(element.children()[0]),
            opened = true;
            title.bind('click', toggle);
            function toggle() {
                opened = !opened;
                element.removeClass(opened ? 'closed' : 'opened');
                element.addClass(opened ? 'opened' : 'closed');
            }
            toggle();
        }
    }
});

Upvotes: 0

Views: 2063

Answers (1)

Heinrich
Heinrich

Reputation: 313

When you want to access your Event through legacy, you should work with the $apply method from angular, like this:

function set_from_legacy(dom_element) {
    var scope = angular.element(dom_element).scope();
    scope.$apply(function() {
         scope.viewmodel_element.property1 = something;
         scope.viewmodel_element.property2 = somethingelse;
    });
}

Then angular should kick in and update your properties in HTML associated with the view model.

e.g. slightly change your template so it has the className bound to the model zippy in the controller (it could of course be an array of zippy's)

hope this helps.

Upvotes: 4

Related Questions