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());
});
}
}
它的工作!這將需要一段時間來弄清楚。我感謝您的幫助。 – Rob 2014-10-07 14:28:32