Getters在Angular Factory方法中返回null

时间:2016-05-27 06:38:18

标签: javascript angularjs variables

我有以下工厂,当我从控制器函数调用setter时,它设置名称但是如果我从控制器调用getter,它将返回null。为什么变量值没有出现?

<div id="fullscreen">

1 个答案:

答案 0 :(得分:0)

基本上你需要了解javascript词法范围。通过javascript词法范围。以下是经过纠正的代码。

<html ng-app="myapp">
<head>
    <title>Fixed :Getters return null in Angular Factory methods</title>
</head>
<body class="debug" ng-controller="mainCtrl">
    {{name}}
    <script src="angular.min.js"></script>
    <script>
        (function () {
            'use strict';

            var app = angular.module('myapp',[]);

            app.factory('myFactory', myFactory);

            myFactory.$inject = ['$http', '$rootScope'];
            var config = {
                // TO DO : check if anything required
            };


            /* @ngInject */
            function myFactory($http, $rootScope) {

                var userName = null; //global
                var userId = null;   //global
                var pwd = null;     //global

                var service = {
                    getUserName: getUserName,
                    setUserName: setUserName,
                    getPwd:getPwd,
                    setPwd:setPwd,
                };
                function getUserName() {
                    console.log("user name.getUserName." + userName);
                    return userName;
                }

                function setUserName(name) { //userName -> local variable
                    console.log("user name.." + name);
                   // userName = userName; //You thing the leftside "userName" is global but its referencing to localvariable. So give it a differnt name. Cheking variable scope in javascript.
                    userName = name;
                }


                function getPwd() {
                    console.log("user getPwd.." + pwd);
                    return pwd;
                }

                function setPwd(password) {  //pwd -> local variable
                    console.log("user setPwd.." + password);
                    //pwd = pwd; //You thing the leftside "pwd" is global but its referencing to local variable. So give a differnt name. Cheking variable scope in javascript.
                    pwd = password;
                }

                return service;
            }

            app.controller('mainCtrl',mainCtrlFn);

            mainCtrlFn.$inject = ['$scope','myFactory'];

            function mainCtrlFn($scope,myFactory) {
                myFactory.setUserName("Sai Ram");
                $scope.name = myFactory.getUserName();
            }
        })();
    </script>
</body>