在html页面中无法访问AngularJS $ rootScope

时间:2016-03-18 04:46:37

标签: html angularjs

我在以下两个链接中寻找解决方案:

how-to-access-rootscope-value-defined-in-one-module-into-another-module

rootscope-variable-exists-but-not-accessible

但仍无法找到解决方案。

我在$rootScope.user函数中初始化$scope.login变量,该函数由我的控制器的其他按钮点击事件触发:

app.controller('LoginFormController',['$rootScope','$location','$log','$scope','userAngService','userBean',function($rootScope,$location,$log,$scope,userAngService,userBean){
    $scope.login = function(val){
        $scope.user = userAngService.login(val).then(function(data){
            $rootScope.user = data;
            $location.path("/home");
        });
    };
 }]);

将其重定向到app.js中映射的/home

    angular.module('Writer', ['AllControllers','ngRoute'])
.config(['$routeProvider', function($routeProvider,$Log){
    $routeProvider.when('/Diary',{
        templateUrl:'login.html',
        controller: 'LoginFormController'
    })
    .when('/home',{
        templateUrl: 'home.html',
        controller: 'ReachController'
     })
    .otherwise({redirectTo : '/Diary'});
}]);

现在我正在访问映射控制器$rootScope.user中的ReachController变量:

app.controller('ReachController',['$scope','$rootScope',function($scope,$rootScope){
    $scope.user = {};
    $scope.user = $rootScope.user;
    console.log($scope.user);
}]);

它完美地在控制台中记录角度对象,但在我的home.html页面中不可用。 这是html页面 - 在<h2><h3>标签中访问它:

&#13;
&#13;
    <div>
        <h2>{{$scope.user}}hhhello</h2>
        <h3>{{$scope.user.author}}</h3>
        <div id="welcomeStory">
            <span id="wsTitleBub">Title</span>
            <input id="wsTitle" type="text" ng-model="wsPublish.welcomeStoryTitle" />{{wsPublish.welcomeStoryTitle}}
            <h6>Words..</h6>
            <textarea id="wsWords" ng-model="wsPublish.welcomeStoryWords"></textarea>
            <input id="wsPublish" type="button" name="wsPublish" value="Publish" ng-click="pub = !pub" />
            <input id="wsAddShelf" type="button" name="wsAddToShelf" value="Add To Shelf" ng-click="addToShelf()" />
        </div>
        <div id="wsPublishTo" ng-show="pub">
            <ul>
                <li>
                    <input type=submit id="wsgroups" value="Group" ng-click="publishGroup(wsPublish)" />
                </li>
                <li>
                    <button id="wsPublic" ng-click="public()">Public</button>
                </li>
            </ul>
        </div>
    </div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

只需将标记中的$scope.user更改为user,即可正常使用。

答案 1 :(得分:0)

在$ rootScope中,您可以使用{{user}}在标记中直接访问它,无需再次将其分配给范围变量!