我试图使用控制器调用一个角度js函数。我正在使用代码:
的index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DevPortal</title>
<script src="js/angular.min.js"></script>
<script src="js/controllers/app.js"></script>
</head>
<body ng-app="devportal">
<div ng-include="'templates/login_menu.html'"></div>
</body>
</html>
app.js
var app = angular.module('devportal', []);
app.controller('AppController', function($scope, $http) {
return{
getuserloginmenu : function(){$http.get('/getuserloginmenu').then(function(response){$scope.loginmenu=response.data;})},
getuserloginmenu1 : function(){$http.get('/getuserloginmenu1').then(function(response){$scope.loginmenu1=response.data;})}
};
});
login_menu.html
<div ng-controller="AppController as ctrl">
<div on-init="ctrl.getuserloginmenu()">
<p ng-repeat="menu in loginmenu">{{menu}}</p>
</div>
</div>
我的rest
服务正常运行并返回String数组。我无法在html中调用/获取其余服务数据。
答案 0 :(得分:0)
你的代码似乎是合法的,唯一制造噪音的东西(至少对我而言)是你为调用函数而添加的on-init
。我认为这就是问题所在。
尝试
<div ng-controller="AppController as ctrl">
<div ng-init="ctrl.getuserloginmenu()">
<p ng-repeat="menu in loginmenu">{{menu}}</p>
</div>
</div>
也许..为了保持清洁:更改控制器的语法(即使它有效)
var app = angular.module('devportal', []);
app.controller('AppController', function($scope, $http) {
$scope.getuserloginmenu = function(){$http.get('/getuserloginmenu').then(function(response){$scope.loginmenu=response.data;})};
$scope.getuserloginmenu1 = function(){$http.get('/getuserloginmenu1').then(function(response){$scope.loginmenu1=response.data;})};
});
编辑:
这是对ng-init的错误使用。我将留下Angular的文档
https://www.w3schools.com/angular/ng_ng-init.asp
但很快,您希望$scope.loginmenu
填充。你不需要等到div加载。当控制器进入时,您可以立即填充$scope.loginmenu
。
查看
<div ng-controller="AppController as ctrl">
<div>
<p ng-repeat="menu in loginmenu">{{menu}}</p>
</div>
</div>
控制器
var app = angular.module('devportal', []);
app.controller('AppController', function($scope, $http) {
$scope.getuserloginmenu = function(){$http.get('/getuserloginmenu').then(function(response){$scope.loginmenu=response.data;})};
$scope.getuserloginmenu1 = function(){$http.get('/getuserloginmenu1').then(function(response){$scope.loginmenu1=response.data;})};
$scope.getuserloginmenu();
});