Mis*_*hko 6 angularjs angularjs-directive
请考虑以下指令:( 现场演示)
app.directive('spinner', function() {
return {
restrict: 'A',
scope: {
spinner: '=',
doIt: "&doIt"
},
link: function(scope, element, attrs) {
var spinnerButton = angular.element("<button class='btn disabled'><i class='icon-refresh icon-spin'></i> Doing...</button>");
element.after(spinnerButton);
scope.$watch('spinner', function(showSpinner) {
spinnerButton.toggle(showSpinner);
element.toggle(!showSpinner);
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
这是这样使用的:
<button ng-click="doIt()" spinner="spinIt">Spin It</button>
Run Code Online (Sandbox Code Playgroud)
当spinner值(即$scope.spinIt本例中的值)是true,该元素应该被隐藏,而spinnerButton应该出现.当spinner值为false,该元素应该是可见的并且spinnerButton应该被隐藏.
这里的问题doIt()是不在孤立的范围内,因此不会在点击时调用.
实施该指令的"Angular方式"是什么?
我的建议是看看这些纺纱厂发生了什么.更专注于API.
相关部分如下.我们使用常规回调来指示我们何时完成,因此微调器知道重置按钮的状态.
function SpinDemoCtrl($scope, $timeout, $q) {
$scope.spinIt = false;
$scope.longCycle = function(complete) {
$timeout(function() {
complete();
}, 3000);
};
$scope.shortCycle = function(complete) {
$timeout(function() {
complete();
}, 1000);
};
}
app.directive('spinnerClick', function() {
return {
restrict: 'A',
scope: {
spinnerClick: "=",
},
link: function(scope, element, attrs) {
var spinnerButton = angular.element("<button class='btn disabled'><i class='icon-refresh icon-spin'></i> Doing...</button>").hide();
element.after(spinnerButton);
element.click(function() {
spinnerButton.show();
element.hide();
scope.spinnerClick(function() {
spinnerButton.hide();
element.show();
});
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
这是一个期望使用的$q.使用Angular风格的异步操作可以更好地工作,并通过在实现promise时重置spinner来消除回调函数.
| 归档时间: |
|
| 查看次数: |
11913 次 |
| 最近记录: |