0

I've been using the controller as syntax and this instead of $scope in my Angular project and ran across an issue using a directive. I'm trying to call a function in my controller using scope.$apply() in the directive. But since I'm not using scope in the controller, I'm getting this error: Uncaught TypeError: undefined is not a function.

I understand why because of the scope issue, but my question is what's the correct way to use $apply in my directive using controller as and this instead of $scope?

JSFiddle Example: http://jsfiddle.net/z6476omb/

angular
    .module('testApp',[])
    .controller('TestCtrl',TestCtrl)
    .directive('updateDirective',updateDirective)


function TestCtrl() {
    var vm = this;
    vm.name = 'Rob'
    vm.updateName = updateName;

    function updateName(new_name) {
        vm.name = 'Robert';
    }
}

function updateDirective() {
    var directive = {
        link: link,
        restrict:'A'
    }

    return directive;

    function link(scope,element,attr) {
        element.on('click',function() {
            console.log('trying to change...');
            scope.$apply(scope.updateName());
        });
    }
}

1 Answer 1

1

One way to do it is to refer to the controller scope using the alias you used: ctrl.

So in your directive, you can do refer to it as: scope.ctrl.updateName()

See fiddle here:

http://jsfiddle.net/z6476omb/1/

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

1 Comment

It worked! It would have taken a while to figure that out. I appreciate your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.