I'm trying to define a directive sortable
which wraps jqueryui's sortable plugin.
The angular code is:
module.directive('sortable', function () {
return function (scope, element, attrs) {
var startIndex, endIndex;
$(element).sortable({
start:function (event, ui) {
startIndex = ui.item.index();
},
stop:function (event, ui) {
endIndex = ui.item.index();
if(attrs.onStop) {
scope.$apply(attrs.onStop, startIndex, endIndex);
}
}
}).disableSelection();
};
});
The html code is:
<div ng-controller="MyCtrl">
<ol sortable onStop="updateOrders()">
<li ng-repeat="m in messages">{{m}}</li>
</ol>
</div>
The code of MyCtrl
:
function MyCtrl($scope) {
$scope.updateOrders = function(startIndex, endIndex) {
console.log(startIndex + ", " + endIndex);
}
}
I want to get the startIndex
and endIndex
in my callback updateOrders
and do something with them, but it prints:
undefined, undefined
How to pass these parameters to my callbacks? Is my approach correct?
This fiddle shows hot callback from a directive passing parameters. Main trick is to use the scope to pass a function. http://jsfiddle.net/pkriens/Mmunz/7/
var myApp = angular.module('myApp', []).
directive('callback', function() {
return {
scope: { callback: '=' },
restrict: 'A',
link: function(scope, element) {
element.bind('click', function() {
scope.$apply(scope.callback('Hi from directive '));
})
}
};
})
function MyCtrl($scope) {
$scope.cb = function(msg) {alert(msg);};
}
Then the html looks like for example:
<button callback='cb'>Callback</button>