2015-07-31 2 views
8

Я использую кнопку spinner при загрузке содержимого, когда пользователь нажимает на содержимое кнопки «Поиск», в это время кнопкаLabel будет изменена на «Поиск» и счетчик (здесь кнопка будет отключена). После загрузки содержимого (Promise resolved) buttonLable вернется к «Поиск» (кнопка будет включена здесь). Я пробовал приведенный ниже код, но он всегда показывает счетчик.AngularJS: добавление кнопки Spinner при загрузке содержимого

HTML:

<button class="btn btn-xs btn btn-blue" ng-click="show()"> 
    <span><i class="glyphicon glyphicon-off"></i></span> {{buttonLabel}} 
</button> 

Сценарий:

$scope.buttonLabel = "Search"; 
$scope.show = function() { 
    $scope.buttonLabel = "Searching"; 
    $scope.test = TestService.getList($cookieStore.get('url'), 
    $rootScope.resourceName+"/students"); 
    $scope.test.then(function(data) { 
     if(data.list) { 
     $scope.testData = data.list; 
     $scope.buttonLabel = "Search"; 
     } 
    } 
    } 

Обновлено Fiddle:http://jsfiddle.net/xc6nx235/18/

ответ

8
<div ng-app="formDemo" ng-controller="LocationFormCtrl"> 
<div> 
    <button type="submit" class="btn btn-primary" ng-click="search()"> 
     <span ng-show="searchButtonText == 'Searching'"><i class="glyphicon glyphicon-refresh spinning"></i></span> 
     {{ searchButtonText }} 
    </button> 
</div> 

Все, что вам нужно сделать, это использовать ng-show или ng-hide директивы.

нг-шоу = "выражение"

<span ng-show="searchButtonText == 'Searching'"> 
    <i class="glyphicon glyphicon-refresh spinning"></i> 
</span> 

этот промежуток будет виден только при searchButtonText будет равна строке 'Searching'.

Вы должны узнать больше о директивах углов.Они будут полезны в будущем.

Удачи.

Demo http://jsfiddle.net/xc6nx235/16/

+0

Спасибо @Jagdeep Singh. Работает. – NNR

+0

@ N123 Вы можете использовать ng-disabled = "expression", чтобы отключить кнопку. –

+0

@ Jagdeep Singh: Обновлена ​​ссылка на скрипку в вопросе. – NNR

1

Просто добавьте ng-show к вашему блесны:

<span ng-show="loading"><i class="glyphicon glyphicon-refresh spinning"></i></span> 

и контроллер:

.controller("LocationFormCtrl", function ($scope) { 
    $scope.searchButtonText = "Search"; 
    $scope.loading = false; 
    $scope.test="false"; 
    $scope.search = function() { 
     $scope.test="true"; 
     $scope.loading="true" 
     $scope.searchButtonText = "Searching"; 
     // Do your searching here 
    } 
}); 

Затем, когда вы получите свой ответ, установите $scope.loading в false снова

Demo

1

Использование ng-show директива как этот ng-show="test" на пролете вращателя:

Отрывок:

// http://icelab.com.au/articles/levelling-up-with-angularjs-building-a-reusable-click-to-edit-directive/ 
 

 
angular.module("formDemo", []) 
 

 
.controller("LocationFormCtrl", function($scope) { 
 
    $scope.searchButtonText = "Search"; 
 
    $scope.test = "false"; 
 
    $scope.search = function() { 
 
    $scope.test = "true"; 
 
    $scope.searchButtonText = "Searching"; 
 
    // Do your searching here 
 
    } 
 
});
</style> <!-- Ugly Hack due to jsFiddle issue:http://goo.gl/BUfGZ --> 
 
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.1.6/css/foundation.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> <script src="https://rawgithub.com/angular-ui/angular-ui/master/build/angular-ui.js"></script> <style> body { 
 
    font-family: "HelveticNeue", sans-serif; 
 
    font-size: 14px; 
 
    padding: 20px; 
 
} 
 
h2 { 
 
    color: #999; 
 
    margin-top: 0; 
 
} 
 
.field { 
 
    margin-bottom: 1em; 
 
} 
 
.click-to-edit { 
 
    display: inline-block; 
 
} 
 
input { 
 
    display: initial !important; 
 
    width: auto !important; 
 
    margin: 0 5px 0 0 !important; 
 
} 
 
.glyphicon.spinning { 
 
    animation: spin 1s infinite linear; 
 
    -webkit-animation: spin2 1s infinite linear; 
 
} 
 
@keyframes spin { 
 
    from { 
 
    transform: scale(1) rotate(0deg); 
 
    } 
 
    to { 
 
    transform: scale(1) rotate(360deg); 
 
    } 
 
} 
 
@-webkit-keyframes spin2 { 
 
    from { 
 
    -webkit-transform: rotate(0deg); 
 
    } 
 
    to { 
 
    -webkit-transform: rotate(360deg); 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="formDemo" ng-controller="LocationFormCtrl"> 
 
    <div> 
 
    <button type="submit" class="btn btn-primary" ng-click="search()"> 
 
     <span ng-show="test"><i class="glyphicon glyphicon-refresh spinning"></i></span> 
 
     {{ searchButtonText }} 
 
    </button> 
 
    </div> 
 
</div>

4

Используйте ng-show, чтобы показать (или нет) загрузчик ng-show="test":

JSFiddle

// http://icelab.com.au/articles/levelling-up-with-angularjs-building-a-reusable-click-to-edit-directive/ 
 

 
angular.module("formDemo", []) 
 

 
.controller("LocationFormCtrl", function ($scope, $timeout) { 
 
    $scope.searchButtonText = "Search"; 
 
$scope.test="false"; 
 
$scope.search = function() { 
 
    $scope.test="true"; 
 
    $scope.searchButtonText = "Searching"; 
 
    $timeout(function(){ 
 
     $scope.test="false"; 
 
     $scope.searchButtonText = "Search"; 
 
    },1000) 
 
    // Do your searching here 
 
} 
 
});
body { 
 
    font-family:"HelveticNeue", sans-serif; 
 
    font-size: 14px; 
 
    padding: 20px; 
 
} 
 
h2 { 
 
    color: #999; 
 
    margin-top: 0; 
 
} 
 
.field { 
 
    margin-bottom: 1em; 
 
} 
 
.click-to-edit { 
 
    display: inline-block; 
 
} 
 
input { 
 
    display: initial !important; 
 
    width: auto !important; 
 
    margin: 0 5px 0 0 !important; 
 
} 
 

 
.glyphicon.spinning { 
 
    animation: spin 1s infinite linear; 
 
    -webkit-animation: spin2 1s infinite linear; 
 
} 
 

 
@keyframes spin { 
 
    from { transform: scale(1) rotate(0deg);} 
 
    to { transform: scale(1) rotate(360deg);} 
 
} 
 

 
@-webkit-keyframes spin2 { 
 
    from { -webkit-transform: rotate(0deg);} 
 
    to { -webkit-transform: rotate(360deg);} 
 
}
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.1.6/css/foundation.min.css"> 
 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> 
 

 
<!-- Optional theme --> 
 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> 
 

 
<!-- Latest compiled and minified JavaScript --> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> 
 
<script src="https://rawgithub.com/angular-ui/angular-ui/master/build/angular-ui.js"></script> 
 
    
 
<div ng-app="formDemo" ng-controller="LocationFormCtrl"> 
 
    <div> 
 
    <button type="submit" class="btn btn-primary" ng-click="search()"> 
 
     <span ng-show="test" ><i class="glyphicon glyphicon-refresh spinning"></i></span> 
 
     {{ searchButtonText }} 
 
    </button> 
 
</div>  
 
</div>

+0

Привет, через 1 секунду текст кнопки изменится, но есть ли способ, чтобы он показывал 'Поиск', пока мы не получим ответ с сервера.? –

0

Вы должны использовать ng-class, чтобы добавить/удалить класс .spinning на основе $scope.test. Я обновил свою скрипку здесь: http://jsfiddle.net/xc6nx235/15/

4

Вы также можете использовать эту простую директиву:

https://rawgit.com/jvdvleuten/angular-button-spinner/master/demo.html

Чтобы использовать его, просто добавьте button-spinner='loading' атрибут:

<button class="btn btn-success" ng-click="show()" button-spinner="loading">Load</button> 

Это добавит кок к он, внутри кнопки, когда ваша переменная loading в области истинна.

0

Для Angular2/4 вы можете использовать [скрытый] для контроля видимости счетчика. Вот Plunker.

<button class="btn btn-primary" (click)="onClickDoSomething()"> 
    <span [hidden]="!spin"> 
     <i class="glyphicon glyphicon-refresh spinning"></i> 
    </span> Do something 
</button> 

Где прядения определяется как:

<style> 
    .spinning { 
    animation: spin 1s infinite linear; 
    } 

    @keyframes spin { 
    from { 
     transform: scale(1) rotate(0deg); 
    } 
    to { 
     transform: scale(1) rotate(360deg); 
    } 
    } 
</style> 

И ваш компонент просто устанавливает логическое значение, чтобы контролировать видимость блесны. В этом примере мы просто вращаемся в течение 10 секунд.

import {Component} from 'angular2/core'; 
import {Observable} from 'rxjs/Rx'; 

@Component({ 
    selector: 'do-something', 
    templateUrl: 'src/dosomething.html' 
}) 
export class DoSomething { 
    private spin: boolean = false; 

    onClickDoSomething() { 
    this.spin = true; 
    this.sub = Observable.interval(10000).subscribe(x => { 
     this.sub.unsubscribe(); 
     this.spin = false; 
    }); 
    } 
} 
Смежные вопросы