gpt4 book ai didi

javascript - 如何在 Controller 中加载指令?

转载 作者:行者123 更新时间:2023-11-30 12:26:33 26 4
gpt4 key购买 nike

基于这个例子throbberDirective , 如何将自定义指令注入(inject) Controller ,以便可以调用函数 show() hide()?我无法摆脱以下错误:

Error: [$injector:unpr] Unknown provider: inputThrobberProvider <- inputThrobber <- landingCtrl

示例代码:

var app = angular.module('myapp', ['ngAnimate', 'ui.router', 'templates']);

app.directive('inputThrobber', [function() {
return {
restrict: 'A',
require: 'ngModel',
controller: function($scope, $element) {
var inputThrobberCtrl = {
show: function() {
$element.addClass('throbbing');
},
hide: function() {
$element.removeClass('throbbing');
}
};

return inputThrobberCtrl;
}
};
}])
.controller('landingCtrl', ['$scope', 'geolocation', 'inputThrobber', function($scope, geolocation, inputThrobber) {

// inputThrobber.show()
geolocation.getAddress().then(function(address) {
$scope.address = address;
}).catch(function(err) {
$scope.error = error;
$scope.address = '';
})
.finally(function() {
// $inputThrobber.hide()
});

}]);

最佳答案

这是一个使用调度事件来显示/隐藏微调器的示例:

app.directive('inputThrobber', [function() {
return {
restrict: 'A',
require: 'ngModel',
controller: function($scope, $element) {
$scope.$on('startThrobbing', function() {
$element.addClass('throbbing');
});
$scope.$on('stopThrobbing', function() {
$element.removeClass('throbbing');
});
}
};
}])

.controller('landingCtrl', ['$scope', 'geolocation', function($scope, geolocation) {
$scope.$broadcast('startThrobbing');
geolocation.getAddress().then(function(address) {
$scope.address = address;
}).catch(function(err) {
$scope.error = error;
$scope.address = '';
})
.finally(function() {
$scope.$broadcast('stopThrobbing');
});
}]);

关于javascript - 如何在 Controller 中加载指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29180782/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com