考虑以下spinner-click
指令:
指令用途:
<button class="btn btn-mini"
ng-class="{'btn-warning': person.active, disabled: !person.active}"
spinner-click="deleteItem($index)"
spinner-text="Please wait..."
spinner-errors="alerts">
Delete
</button>
指示:
app.directive('spinnerClick', function() {
return {
restrict: 'A',
scope: true,
link: function(scope, element, attrs) {
var originalHTML = element.html();
var spinnerHTML = "<i class='icon-refresh icon-spin'></i> " + attrs.spinnerText;
element.click(function() {
if (element.is('.disabled')) {
return;
}
element.html(spinnerHTML).addClass('disabled');
scope.$apply(attrs.spinnerClick).then(function() {
element.html(originalHTML).removeClass('disabled');
}, function(errors) {
element.html(originalHTML).removeClass('disabled');
// This is ugly! Is there a better way?
var e = scope[attrs.spinnerErrors];
e.length = 0;
e.push.apply(e, errors);
});
});
}
};
});
控制器:
app.controller('MainCtrl', function($scope, $q, $timeout) {
$scope.alerts = ['First alert'];
$scope.people = [
{ name: 'David', active: true },
{ name: 'Layla', active: false }
];
$scope.deleteItem = function(index) {
var defer = $q.defer();
$timeout(function() {
defer.reject(["Something 'bad' happened.", "Check your logs."]);
}, 2000);
return defer.promise;
};
});
注意: spinner-click
可以与其他指令一起使用(例如ng-class
在本例中)。
如您所见,我$scope.alerts
在指令中设置了一种非常讨厌的方式。你能找到更好的方法来做到这一点吗?
更新 :(演示)
我试着这样使用$parse
:
var errorsModel = $parse(attrs.spinnerErrors);
errorsModel.assign(scope, errors);
这不起作用。
但是,如果我有spinner-errors="wrapper.alerts"
而不是spinner-errors="alerts"
,它确实有效!
有没有办法避免使用包装器?