我是一个角色如此裸露的新手,我会尽力表达我想要实现的目标。
我有两个网页;一个主要的登录'页面和辅助'关于'页。 about页面只不过是一个带有HTML文本的页面。我只使用ng-href链接访问这两个页面。
我有一项服务可以记住一些用户登录详细信息,当我点击关于页面然后返回主页时,这些信息似乎仍然存在。
但是,当用户点击返回主页面时,我不知道如何调用函数。此函数将是主控制器范围内的登录功能。然后,我将使用服务中的用户详细信息自动登录并显示用户信息。
This线程似乎非常相似,但用户似乎处于比我更高级的阶段。
main.html中
<div class="main">
<div class="content" ng-hide="login">
<form>
... login fields ...
<button ng-click="$login()">Log in</button>
</form>
</div>
<div class="content" ng-show="login">
<form>
... user info ...
</form>
</div>
<div class="footer">
<a ng-href="#/about"/>About</a>
</div>
</div>
About.hml
<div class="about">
<div class="content">
... plain HTML ...
</div>
<div class="footer">
<a ng-href='#/main'/>mAIN</a>
</div>
</div>
app.js
&#39;
use strict';
angular.module('sguAppApp', [
'ngResource',
'ngSanitize',
'ngRoute',
'ngAnimate'
])
.constant( 'eURL', '....webpage...' )
.config(function ($routeProvider) {
$routeProvider
.when('/main', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.otherwise({
redirectTo: '/main'
});
});
main.js
angular.module('App')
.service('TestService', function() {
var TestService = {};
TestService.testVar1 = '';
TestService.testVar2 = '';
TestService.testVar3 = ''
return TestService;
})
.controller('MainCtrl', function ($scope, $rootScope, .... TestService) {
$scope.user = {};
$scope.user.logon = '';
$scope.user.password = '';
$scope.sData = '';
$scope.$login = function () {
$scope.loading = true;
... do stuff to testVarNs ...
}
}
.controller('AboutCtrl', function ($rootScope, $scope, TestService) {
... somehow call $login function in MainCtrl using the testVarNs in the service ...
(not sure if this is even needed)
})
答案 0 :(得分:1)
您放置的方式,无论是在MainCtrl还是AboutCtrl的上下文中,当您从一个页面导航到另一个页面时,现有的上下文都会被破坏,而目标的上下文会被实例化。
登录功能可能应该存在于服务中,这样您就可以从任何地方调用它。
通过这种方式,您可以在控制器中注入TestService并调用该函数以响应点击,例如,使用ng-click =&#34; TestService。$ login()&#34;
另一种方法可能是让另一个控制器位于包含MainCtrl或AboutCtrl的上下文中,说出你在html文件中早期定义的AppCtrl,例如:
&LT; body ng-controller =&#34; AppCtrl&#39;&gt; ...
现在,AppCtrl上下文中定义的属性在子上下文中是可见的,因此如果您定义了$ login函数,则可以调用它。