我尝试在angularjs中创建服务,但我一直在获得angular.js:10467错误:[ng:areq]参数'MainController'不是函数,未定义。
HTML:
<div ng-controller="MainController">
<form name="searchUser" method="post">
<input ng-model="username" type="search" placeholder="Find"/>
<input type="submit" value="Search" ng-click="search(username)" />
</form>
You are searching for: {{username}}
<hr />
<div ng-repeat="(key,value) in data">
{{ key + " : " + value}}
</div>
</div>
<script src="lib/angular/angular.js"></script>
<script src="js/app.js"></script>
<script src="services/Screamer.js"></script>
我的app.js:
angular.module('NoteTaker', []); // dependcies in array.
angular.module('NoteTaker', []).controller('MainController', function(screamer, $log, $http, $scope, $interval){
$http({
method : 'GET',
url: 'https://api.github.com/users/' + $scope.username
}).then(function(response){
console.log(response);
$scope.data = response.data;
}, function(response){
console.log(response);
});
我在service.js的服务
(function() {
'use strict';
angular.module('NoteTaker', []).factory('screamer', function(){
return {
say: "blahbalh"
};
});
}());
答案 0 :(得分:5)
angular.module(name, dependencies)
创建新模块。如果要添加到现有帐户,请使用angular.module(name)
:
angular.module('NoteTaker', []); // dependcies in array.
angular.module('NoteTaker')
.controller('MainController', function(screamer, $log, $http, $scope, $interval) {
$http({
method: 'GET',
url: 'https://api.github.com/users/' + $scope.username
}).then(function(response) {
console.log(response);
$scope.data = response.data;
}, function(response) {
console.log(response);
});
});
// service.js
(function() {
'use strict';
angular.module('NoteTaker').factory('screamer', function() {
return {
say: "blahbalh"
};
});
}());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="NoteTaker" ng-controller="MainController">
<form name="searchUser" method="post">
<input ng-model="username" type="search" placeholder="Find" />
<input type="submit" value="Search" ng-click="search(username)" />
</form>
You are searching for: {{username}}
<hr />
<div ng-repeat="(key,value) in data">
{{ key + " : " + value}}
</div>
</div>
&#13;
我在第1行创建了一个新模块,并添加了控制器&amp;为它服务。
答案 1 :(得分:0)
tcooc回答了你的问题,但我会尝试让它更容易理解:
app.module('myModule', ['dep1', 'dep2']); // passing an array creates a NEW module
通过调用相同的方法访问新创建的模块,但没有依赖项数组:
app.module('myModule')
.controller('MyController')
.service('MyService')
.factory('MyFactory');
或者,只需将所有内容附加到第一个模块调用:
app.module('myModule', ['dep1', 'dep2'])
.controller('MyController', function(...) {})
.service('MyService', function(...) {})
.factory('MyFactory', function(...) {});
此外,编写依赖注入有助于:
MyController.$inject = ['$scope', '$location', '$log'];
function MyController($scope, $location, $log) {
}
MyService.$inject = ['$http'];
function MyService($http) {
}
这清楚地说明了注入的地方。它使你的代码更具可读性,因为你现在可以这样写:
app.module('myModule', ['dep1', 'dep2'])
.controller('MyController', MyController)
.service('MyService', MyService);