12

我正在尝试定义一个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();
    };
});

html代码是:

<div ng-controller="MyCtrl">
    <ol sortable onStop="updateOrders()">
         <li ng-repeat="m in messages">{{m}}</li>
    </ol>
</div>

的代码MyCtrl

function MyCtrl($scope) {
    $scope.updateOrders = function(startIndex, endIndex) {
        console.log(startIndex + ", " + endIndex);
    }
}

我想在我的回调中获取startIndexand并对它们做一些事情,但它会打印:endIndexupdateOrders

undefined, undefined

如何将这些参数传递给我的回调?我的方法正确吗?

4

4 回答 4

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);};
}

然后 html 看起来像例如:

<button callback='cb'>Callback</button>
于 2012-12-13T08:50:55.240 回答
16

scope.$apply接受函数或字符串。在这种情况下,使用函数会更简单:

  scope.$apply(function(self) {
    self[attrs.onStop](startIndex, endIndex);
  });

不要忘记将您的 html 代码更改为:

<ol sortable onStop="updateOrders">

(删除了()

于 2012-10-09T23:57:14.930 回答
13

备选方案 1

如果您没有此指令的隔离范围,我会为此使用 $parse 服务:

在控制器中:

...
$scope.getPage = function(page) {

   ...some code here...

}

在视图中:

<div class="pagination" current="6" total="20" paginate-fn="getData(page)"></div>

在指令中:

if (attr.paginateFn) {
   paginateFn = $parse(attr.paginateFn);
   paginateFn(scope, {page: 5})
}

备选方案 2

现在,如果您有一个隔离范围,您可以将参数作为命名映射传递给它。如果您的指令是这样定义的:

scope: { paginateFn: '&' },

link: function (scope, el) {
   scope.paginateFn({page: 5});
}
于 2013-11-13T17:10:39.013 回答
0

让@Peter Kriens answser 更进一步,您可以在范围内检查 a 的名称并直接调用它。

var myApp = angular.module('myApp', []).
directive('anyOldDirective', function() {
    return { 
        link: function(scope, element) {
            element.bind('click', function() {
                if (scope.wellKnownFunctionName) {
                      scope.wellKnownFunctionName('calling you back!'); 
                } else {
                      console.log("scope does not support the callback method 'wellKnownFunctionName');
                }
            })
        }
    };
})

function MyCtrl($scope) {
    $scope.wellKnownFunctionName= function(a) {console.log(a);};
}
于 2013-01-18T07:02:12.603 回答