AngularJS控制器,而不是$ scope调用$应用在指令中

问题描述:

我一直在使用控制器作为语法,而不是在我的Angular项目中使用$scope,并使用指令运行问题。我试图在指令中使用scope.$apply()来调用我的控制器中的函数。但由于我没有在控制器中使用范围,我得到这个错误:Uncaught TypeError:undefined不是一个函数。

我明白为什么,因为范围问题,但我的问题是什么是正确的方式来使用$apply在我的指令使用控制器作为和这而不是$scope

的jsfiddle实施例: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()); 
     }); 
    } 
} 

一种方式做到这一点是使用您使用的别名参考控制器范围:ctrl

所以在你的指令,你可以做称其为:scope.ctrl.updateName()

在这里看到小提琴:

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

+0

它的工作!这将需要一段时间来弄清楚。我感谢您的帮助。 – Rob 2014-10-07 14:28:32