[英]Angularjs pass function from Controller to Directive (or call controller function from directive) - with parameters
我的問題很簡單,我只想將控制器函數傳遞給指令。 換句話說,我只想從指令中調用控制器函數。
var myapp =angular.module('myapp',[]); myapp.controller('myCtrl',['$scope','$timeout',function($scope,$timeout){ $scope.fnItemsOnAdded = function(itms){ alert('Hi, I am in controller add. Here are your Items: '+JSON.stringify(itms)); } $scope.fnItemsOnCancel = function(itms){ alert('Hi, I am in controller cancel. Here are your Items: '+JSON.stringify(itms)); } }]); myapp.directive('myPicker',['$timeout',function($timeout){ var dtv={}; dtv.template = '<li ng-repeat="itm in ngModel.ItemsList"><label><input type="checkbox" ng-model="itm.IsSelected" />{{itm.Name}}</label></li>'; dtv.template += '<a href="javascript:void(0)" ng-click="addItems()" class="addItems">add items</a>'; dtv.template += '<a href="javascript:void(0)" ng-click="cancelItems()" class="cancel">cancel</a>'; dtv.scope = { postUrl: '@', jsonadd: '&', jsoncancel: '&' }; dtv.restrict = 'A'; dtv.link = function($scope,elm,attrs){ $scope.ngModel={}; $scope.ngModel.SelectedKeys=[]; $timeout(function(){ $scope.ngModel.ItemsList = [ {Name:"Item1",IsSelected:false}, {Name:"Item2",IsSelected:false}, {Name:"Item3",IsSelected:false}, {Name:"Item4",IsSelected:true}, {Name:"Item4",IsSelected:false}, ]; },100); $scope.addItems = function(){ //Dummy logic to update SelectedKeys for(var idx =0;idx<$scope.ngModel.ItemsList.length;idx++){ if($scope.ngModel.ItemsList[idx].IsSelected){ $scope.ngModel.SelectedKeys.push($scope.ngModel.ItemsList[idx]); } } alert("i'm in directive add. Lemme call parent controller"); $scope.jsonadd($scope.ngModel.SelectedKeys); } $scope.cancelItems = function(){ alert("i'm in directive cancel. Lemme call parent controller"); $scope.jsonadd($scope.ngModel.SelectedKeys); } } return(dtv); }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myapp" ng-controller="myCtrl"> <div class="jqmWindow" id="myPickListDiv" my-picker jsonadd="fnItemsOnAdded" jsoncancel="fnItemsOnCancel" post-url="/myurl"></div> </div>
誰能幫我在哪里我錯了。 我相信它與$ scope繼承或約定有關。
我知道我在這里犯了一些小錯誤,只是因為我趕不上忙才知道。
非常感謝您的幫助!
你快到了。 傳遞參數的語法有點奇怪。
在您的HTML中,使用類似
<div my-picker jsonadd="fnItemsOnAdded(items)"...
在你的指令中
$scope.jsonadd({items: $scope.ngModel.SelectedKeys})
傳遞給隔離作用域函數( jsonadd
和jsoncancel
)的對象中的鍵需要與屬性中使用的參數名稱匹配。
我不知道SelectedKeys
來源,但我想為了簡潔起見,您已經省略了一些內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.