我的问题很简单,我只想将控制器函数传递给指令。换句话说,我只想从指令调用控制器函数。
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);
}]);
&#13;
<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>
&#13;
任何人都可以帮助我,我在这里出错了。我相信它与$ scope继承或约定有关。
我知道我在这里犯了一些小错误,只是因为我无法在匆忙中解决这个问题。
非常感谢你的帮助!
答案 0 :(得分:5)
你快到了。传递params的语法有点奇怪。
在您的HTML中,使用类似
的内容<div my-picker jsonadd="fnItemsOnAdded(items)"...
并在你的指令......
$scope.jsonadd({items: $scope.ngModel.SelectedKeys})
传递给隔离范围函数(jsonadd
,jsoncancel
)的对象中的键需要匹配属性中使用的参数名称。
我不知道SelectedKeys
来自哪里,但我认为你为了简洁而省略了一些东西。