Fre*_*ind 12 directive jquery-ui-sortable angularjs
我正在尝试定义一个sortable包装jqueryui的可排序插件的指令.
角度代码是:
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();
};
});
Run Code Online (Sandbox Code Playgroud)
html代码是:
<div ng-controller="MyCtrl">
<ol sortable onStop="updateOrders()">
<li ng-repeat="m in messages">{{m}}</li>
</ol>
</div>
Run Code Online (Sandbox Code Playgroud)
代码MyCtrl:
function MyCtrl($scope) {
$scope.updateOrders = function(startIndex, endIndex) {
console.log(startIndex + ", " + endIndex);
}
}
Run Code Online (Sandbox Code Playgroud)
我想在我的回调中得到它startIndex并用它们做一些事情,但它打印出来:endIndexupdateOrders
undefined, undefined
Run Code Online (Sandbox Code Playgroud)
如何将这些参数传递给我的回调?我的方法是否正确?
Pet*_*ens 19
这个小提琴显示来自传递参数的指令的热回调.主要技巧是使用范围来传递函数. 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);};
}
Run Code Online (Sandbox Code Playgroud)
然后html看起来像例如:
<button callback='cb'>Callback</button>
Run Code Online (Sandbox Code Playgroud)
Tos*_*osh 16
scope.$apply接受函数或字符串.在这种情况下,使用函数会更简单:
scope.$apply(function(self) {
self[attrs.onStop](startIndex, endIndex);
});
Run Code Online (Sandbox Code Playgroud)
不要忘记将您的HTML代码更改为:
<ol sortable onStop="updateOrders">
Run Code Online (Sandbox Code Playgroud)
(删除了())
Edm*_*ake 13
备选方案1
如果你没有这个指令的隔离范围,我会使用$ parse服务:
在控制器中:
...
$scope.getPage = function(page) {
...some code here...
}
Run Code Online (Sandbox Code Playgroud)
在视图中:
<div class="pagination" current="6" total="20" paginate-fn="getData(page)"></div>
Run Code Online (Sandbox Code Playgroud)
在指令中:
if (attr.paginateFn) {
paginateFn = $parse(attr.paginateFn);
paginateFn(scope, {page: 5})
}
Run Code Online (Sandbox Code Playgroud)
备选方案2
现在,如果您有隔离范围,则可以将参数作为命名映射传递给它.如果您的指令定义如下:
scope: { paginateFn: '&' },
link: function (scope, el) {
scope.paginateFn({page: 5});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15127 次 |
| 最近记录: |