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());
});
}
}