gpt4 book ai didi

angularjs - Angular : Error: Unknown provider during module. 配置()

转载 作者:行者123 更新时间:2023-12-04 01:35:04 25 4
gpt4 key购买 nike

我得到 Uncaught Error: Unknown provider: testProvider from myApp在下面的代码中:
test是一个自定义提供者。

angular.module('myApp', [])
.config(function (testProvider) {
testProvider.setPrefix("works: ");
});

完整代码在这里:
angular.module('myApp', [])
.config(function (testProvider) {
testProvider.setPrefix("works: ");
});


angular.module('myApp')
.provider ("test", function () {
var prefix;
this.setPrefix = function(p) {
prefix = p;
}

this.$get = function () {
return {
log: function(msg) {
console.log (prefix + msg);
}
}
}
});

angular.module('myApp')
.controller ("myCtrl", function($scope, test) {
$scope.$watch ('myModel', function (newval) {
test.log(newval);
})
});

Plunker 链接: http://plnkr.co/edit/zcIHRn?p=preview

最佳答案

调用

module.provider("test", ...);

真的是一个呼唤

module.config(function($provide) {
$provide.provider("test", ...);
});

(请参阅我的 wiki article on dependency injection 了解更多详情。)

自从 config block 按照它们被声明的顺序运行,你只需要将你的提供者的声明移动到它的使用点之上。你会经常看到它写成这样:

angular.module('myApp', [])
.provider ("test", function () {
var prefix;
this.setPrefix = function(p) {
prefix = p;
}

this.$get = function () {
return {
log: function(msg) {
console.log (prefix + msg);
}
}
}
})
.config(function (testProvider) {
testProvider.setPrefix("works: ");
})
.controller ("myCtrl", function($scope, test) {
$scope.$watch ('myModel', function (newval) {
test.log(newval);
})
});

一个例子: http://plnkr.co/edit/AxTnGv?p=preview

如果您真的想将关注点分开,您可以创建一个新模块并设置依赖项:

angular.module('logging', [])
.provider ("test", function () {
var prefix;
this.setPrefix = function(p) {
prefix = p;
}

this.$get = function () {
return {
log: function(msg) {
console.log (prefix + msg);
}
}
}
})

angular.module('myApp', ['logging'])
.config(function (testProvider) {
testProvider.setPrefix("works: ");
})
.controller ("myCtrl", function($scope, test) {
$scope.$watch ('myModel', function (newval) {
test.log(newval);
})
});

示例: http://plnkr.co/edit/PWtDFG?p=preview

关于angularjs - Angular : Error: Unknown provider during module. 配置(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18350416/

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