简体   繁体   English

加载指令时如何实现禁用

[英]How to implement a disable when loading directive

Hi I have a variable on my scope named loadingdata. 嗨,我在我的作用域上有一个名为loadingdata的变量。 It will have the values true or false to determine if data is loading or not. 它将具有true或false值来确定是否正在加载数据。 I would like to put an attribute on an element to disable it if data is loading. 如果要加载数据,我想在元素上放置一个属性以禁用它。 Here is the code I already have but it is not working: 这是我已经拥有的代码,但是无法正常工作:

module.directive('disableWhenLoadingData', function () {
            return {
                restrict: 'A',
                scope: {},
                link: function ($scope, element, attrs) {
                    $scope.$watch('loadingData', function(newValue, oldValue) {
                        element.attr('disabled', newValue);
                    });
                }
            };
        });

any ideas 有任何想法吗

您可以使用Angular自己的ngDisabled指令,而不用编写自己的指令。

Service: 服务:

module.factory('GetDataService', function ($http) {
    return {
        getCustomers: function() {
            return $http({ url: '/someurl', method: 'GET'});
        }
    }
});

Directive: 指示:

 module.directive('disableWhenLoadingData', function (GetDataService) {
        return {
            restrict: 'A',
            scope: {},
            link: function ($scope, element, attrs) {
                $scope.loadingData = true;
                GetDataService.getCustomers().success(function (data) {
                    $scope.loadingData = false;
                });
            }
        };
    });

Generally I set $scope.loading in my controller, and my button or whatever i set ng-disabled. 通常,我在控制器中设置$ scope.loading,并设置按钮或设置为ng-disabled的任何设置。

In my controller: 在我的控制器中:

$scope.loadData = function () {
    $scope.loading = true;
    $http
        .get('url')
            .success(function (ret) {
                $scope.loading = false;
            });
}

In my view: 在我看来:

<button ng-disabled="loading" ng-click="loadData()">{{loading? 'loading Data' : 'Submit'}}</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM