[英]AngularJS directive won't detect controller scope that binds variables using “this”
我有以下angularJS控制器和指令:
angular.module('twitterApp', [])
.controller('AppCtrl', AppCtrl)
.directive('enter', EnterFunc);
function AppCtrl($scope) {
$scope.loadMoreTweets = function() {
alert('loading more tweets!');
}
}
function EnterFunc() {
return function(scope, element, attrs) {
element.bind('click', function() {
scope.loadMoreTweets();
});
}
}
和以下HTML
<body ng-app="twitterApp">
<div class="container" ng-controller="AppCtrl">
<div enter>
Roll over to load more tweets
</div>
</div>
</body>
現在,這很完美,因為我所做的只是從指令訪問控制器的作用域。 但是,我正在嘗試調整控制器以將變量綁定到“ this”范圍,因此我可以在html上使用“ controller as”語法以使其更易於閱讀,但是,當我將控制器功能更改為以下內容時:
function AppCtrl() {
var vm = this;
vm.loadMoreTweets = function() {
alert('loading more tweets!');
}
}
我的示例停止工作,並且在單擊指令時出現以下錯誤:
Uncaught TypeError: scope.loadMoreTweets is not a function
有人可以解釋如何使此指令生效而無需回到綁定到$ scope嗎? 這是不工作的“ Controller As”版本的Plunkr: http ://plnkr.co/edit/PyIA4HVOMLn0KNJ5V2bc?p=info
我暫時修復了該問題,但是發布了解決方案,以防其他人偶然發現。 為了解決這個問題,我沒有在指令上使用“ scope.loadMoreTweets()”,而是使用了“ scope.ctrl.loadMoreTweets()”。 甚至很難做到這一點,我也很高興沒有“ .ctrl”也無法訪問父作用域,因為“。$ parent”也不起作用。 如果有人有更好的解決方案,請告訴我。 應該有更多關於將指令與Controller的Controller As語法一起使用的文檔。
我已經修改了您的代碼,以將要傳遞給指令的控制器范圍傳遞給引用。 然后,您可以在引用上調用該方法。 看看這是否適合您
指示:
function EnterFunc() {
return {
restrict: 'A',
scope: {
controller: '='
},
link: link
}
function link(scope, element, attrs) {
element.bind('click', function() {
//scope.$apply(attrs.action);
scope.controller.loadMoreTweets();
});
}
}
HTML:
<body ng-app="twitterApp">
<div class="container" ng-controller="AppCtrl as ctrl">
<div enter controller="ctrl">
Roll over to load more tweets
</div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.