使用ng-submit,我試圖在我的MainController中調用一個函數。但是,函數搜索沒有被調用。我假設我需要angularify我的功能,但不知道如何。用'ControllerAs'語法使用ng-submit調用一個函數
的index.html
<html ng-app="main">
<head>
<script src="angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainController as mainCtrl">
<p>{{mainCtrl.message}}</p>
<div>
{{mainCtrl.error}}
</div>
<form ng-submit="search()">
<input type="search" required placeholder="Username to find" ng-model="mainCtrl.username"/>
<input type="Submit" value="Search"/>
</form>
<div>Name: {{mainCtrl.user.name}}</div>
<div>Location: {{mainCtrl.user.location}}</div>
<div>
<img ng-src="{{mainCtrl.user.avatar_url}}" title="{{mainCtrl.user.name}}"/>
</div>
</body>
</html>
的script.js
(function() {
angular.module("main", [])
.controller("MainController", ["$scope", "$http",MainController]);
function MainController($scope, $http) {
function onUserComplete($response) {
$scope.user = $response.data;
};
function onError(reason) {
$scope.error = "Could not fetch the user";
};
function search() {
$http.get("https://api.github.com/users/" + this.username)
.then(onUserComplete, onError);
console.log("1");
};
$scope = this;
this.message = "GitHub viewer!";
this.username = "angular";
};
}());
'search'不在'$ scope'中... – elclanrs
因爲您在ng控制器中使用了...'as',所以您可以使用mainCtrl.search()來調用它。 https://docs.angularjs.org/api/ng/directive/ngController –
我將其更改爲mainCtrl.search(),並沒有解決任何問題。必須也是別的東西? – LinhSaysHi