2014-10-07 105 views
0

我一直在使用控制器作爲語法,而不是在我的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()); 
     }); 
    } 
} 

回答

1

一種方式做到這一點是使用您使用的別名參考控制器範圍:ctrl

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

在這裏看到小提琴:

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

+0

它的工作!這將需要一段時間來弄清楚。我感謝您的幫助。 – Rob 2014-10-07 14:28:32

相關問題