我是Angular的新手。我想在我的控制器中将变量query
设置为null
并将imgType
设置为"illustration"
,但它会抛出:
未捕获的TypeError:无法设置未定义的属性'query'。
你知道什么是错的吗?一切都有效
我正在使用AngularJS 1.4.3
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body ng-app="ilustracka">
<!--Controller-->
<div ng-controller="SearchController as searchCtrl" ng-cloak>
<!--Searching-->
<form ng-submit="searchCtrl.search()">
<input type="text" ng-model="searchCtrl.query" placeholder="search...">
<select ng-model="searchCtrl.imgType">
<option value="illustration" selected>ILU</option>
<option value="image">IMG</option>
</select>
<button type="submit">SEARCH</button>
</form>
<!--Summary result--
<summary></summary>-->
<!--Result-->
<output></output>
</div>
<!--JavaScripts-->
<script src="libs/angularjs/angular.min.js"></script>
<script src="scripts/ilustracka.js"></script>
<script src="scripts/searchController.js"></script>
<script src="scripts/outputDirective.js"></script>
<script src="scripts/searchApiService.js"></script>
</body>
</html>
控制器
(function () {
'use strict';
angular
.module('ilustracka')
.controller('SearchController', SearchController);
//load service searchApi
SearchController().$inject['searchApi'];
function SearchController(searchApi) {
var vm = this;
/*
* vars
*/
vm.query = null;//search string
vm.imgType = 'illustration';//type of search image - (ilu|img)
vm.images = null;//result of query - empty object
vm.result = null;//showing result or info message
/*
* functions
*/
vm.search = search;
function search(){
//!empty searchQuery
if(vm.query){
searchApi.searchImg(vm.query, vm.imgType);
vm.images = searchApi.getImages();
vm.result = searchApi.getResult();
}
}
}
}());
ilustracka
(function(){
"use strict";
angular
.module("ilustracka", []);
}());
答案 0 :(得分:1)
您的问题是如何将searchApi
服务注入您的控制器。 $inject
不是方法,但属性和正确的语法应为:
SearchController.$inject = ['searchApi'];
使用原始代码SearchController().$inject['searchApi'];
,它会抛出未处理的错误,因为SearchController()
(函数调用的结果)返回undefined
,而undefined没有属性$inject
。但是,它不会阻止进一步的控制器实例化,但随后会发生新错误 - 由于缺少依赖注入而导致未知提供程序。这会阻止正确的控制器实例创建。
答案 1 :(得分:0)
//您必须创建传递依赖关系数组的app模块,空是否为空。 angular.module(&#39; ilustracka&#39;,[])//添加空括号
http://jsbin.com/riyozu/edit?html,js,output
(function () {
'use strict';
angular
.module('ilustracka', [])
.controller('SearchController', ['searchAPi', function (searchApi) {
var vm = this;
vm.query = null;//search string
vm.imgType = 'illustration';//type of search image - (ilu|img)
vm.images = null;//result of query - empty object
vm.result = null;//showing result or info message
function search() {
if (vm.query) {
searchApi.searchImg(vm.query, vm.imgType);
vm.images = searchApi.getImages();
vm.result = searchApi.getResult();
}
}
vm.search = search;
}]);
}());