Javascript 如何在加载指令时实现禁用

Javascript 如何在加载指令时实现禁用,javascript,angularjs,Javascript,Angularjs,您好,我的作用域中有一个名为loadingdata的变量。它将具有true或false值,以确定数据是否正在加载。我想在元素上添加一个属性,以便在加载数据时禁用它。以下是我已经拥有的代码,但它不起作用: module.directive('disableWhenLoadingData', function () { return { restrict: 'A', scope: {},

您好,我的作用域中有一个名为loadingdata的变量。它将具有true或false值,以确定数据是否正在加载。我想在元素上添加一个属性,以便在加载数据时禁用它。以下是我已经拥有的代码,但它不起作用:

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

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

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

服务:

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

 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;
                });
            }
        };
    });
服务:

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

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

通常,我在控制器中设置$scope.loading,并禁用我的按钮或任何我设置的ng

在我的控制器中:

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

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

通常,我在控制器中设置$scope.load,并禁用我的按钮或任何我设置的ng

在我的控制器中:

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

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

看起来您没有在
范围
选项中为其设置任何绑定:
范围:{loadingData:'='}
?(当然,您还必须在视图中设置该属性)看起来您没有在
scope
选项中为其设置任何绑定:
scope:{loadingData:'='}
?(当然,您还必须在视图中设置该属性)