如何在显示之前使用角度控制器填充HTML

时间:2019-05-10 23:07:57

标签: javascript angularjs

我试图在显示html之前,然后在按钮单击(提交)之前,基于ng-controller属性预加载数据。我是angular js的新手,不确定如何完成任务。

会有一个问题,有n个答案选项

可能在代码中看到了最后一次尝试,但是除了单击按钮之外,我还需要进入控制器。在显示html之前,我需要先查看问题和可能的答案。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="http://home-dev.kmhp.com/global/js/AngularJS/angularjs.min.1.7.5.js"></script>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular-route.min.js"></script>
    <script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/app.js"></script>
   <script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/Controllers/vote.js"></script> 
   <!--<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/Controllers/HomePageVoteController.js"></script>-->
    <script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/services/vote.js"></script>
    <script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/services/route.js"></script>
   <script>
        // app
        var app = angular.module('quickSurveyApp', ["ngRoute"]);

        // controller(s)
        app.controller("VoteCtrl", ["$scope", "qa", "$location", function ($scope, qa, $location) {
        //app.controller("VoteCtrl", ["$scope", "qa", "$location", function ($scope, qa, $location) {
         //   app.factory("VoteService", ["$scope", "qa", "$location", function ($scope, qa, $location) {
                $scope.activeQuestions = qa.activeQuestions;
                $scope.records = qa.records;
                $scope.QuestionText = qa[0].QuestionText;
                $scope.AnswerText = qa[0].AnswerText;
                $scope.Answers = qa[0].Answers;

                $scope.error = false;
                $scope.AddVote = function () {
                    $scope.error = !!$scope.answer;
                }
            }]);

            // service(s)
            app.factory("VoteService", ["$http", "$q", function ($http, $q) {
                res.setHeader('Access-Control-Allow-Origin', '*');
                var service = {};
                //Gets all data for page.
                var questionNumber = 0;
                service.pageInit = function () {
                    var deferred = $q.defer();
                    $http.get('/API/quick-survey/api/Question/GetQuestionsByZone/0').then(function (response) {
                        deferred.resolve(response.data);
                    }, function (error) {
                        console.error(error);
                        deferred.reject("error");
                    });
                    return deferred.promise;
                };
                return service;
            }]);

            // route(s)
            app.config(["$routeProvider", function ($routeProvider) {
                $routeProvider
                .when("/", {
                    templateUrl: "/api-test-pages/Quick Survey/survey.html",
                    //controller: "VoteCtrl",
                    controller: "VoteCtrl",
                    // it's is good to download the data before displaying the template without the data
                    // so all we found in resolve is gonna be "resolved" before display the page and running the controller
                    resolve: {
                        qa: ["VoteService", "$route", function (VoteService, $route) {
                            return VoteService.pageInit();
                        }]
                    }

                }).
                otherwise({
                    redirectTo: '/'
                });
            }]);


    </script> 



</head>
<body ng-app="quickSurveyApp">
    <div>
        <h1>Quick Survey</h1>
        <div ng-view></div>
    </div>
</body>
</html>

var app = angular.module("quickSurveyApp", ["ng-Route"]);
app.config(["$routeProvider", function ($routeProvider) {
    //res.setHeader('Access-Control-Allow-Origin', '*');
    $routeProvider

       .when("/", {
           templateUrl: "/api-test-pages/Quick-Survey/survey.html",
           //templateUrl: "/API/quick-survey/api-test-pages/Quick Survey/survey.html",
           controller: "VoteCtrl",

           resolve: {
               qa: ["VoteService", "$route", function (VoteService, $route) {
                  // return VoteService.pageInit(1);
                   return VoteService.pageInit();
               }]
           }
           })
        .when("/question/:q", {
            templateUrl: "templates/survey.tpl",
            controller: "VoteCtrl",
            resolve: {
                qa: ["VoteService", "$route", function (VoteService, $route) {
                    var questionNumberFromURL = $route.current.params.q;
                    //return VoteService.pageInit(questionNumberFromURL);
                    return VoteService.pageInit();
                }]
            }
        })
        .when("/thanks", {
            templateUrl: "templates/home.tpl",
            controller: ["$timeout", "$scope", "$location", function ($timeout, $scope, $location) {
                $scope.message = "Thank you !!!";
                $timeout(function () {
                    $location.path("/");
                }, 3000);
            }]
        }).
        otherwise({
            redirectTo: '/xxxx.html'
        });

var app = angular.module('quickSurveyApp', ["ngRoute"]);

function SetCookiesForDebugging() {
    var thecookie = "departid=351&jobtitle=Digital+Developer&floor=0&username=ij25405&ps%5Fdeptname=Digital+Experience&ps%5Fdeptid=351&cost%5Fcenter=351&birthday%5Fday=16&birthday=0&fsla=&nbsp&psdeptname=Digital+Experience&managerwholename=Lawrence+Raffel&area=215&mailstop=%2D+None+Selected+%2D&managerid=21286&departmentid=0&extension=2158635597&emplid=08636&managerusername=LR22638&deptname=KY+Exec+Dir&cubeoffice%5Fno=+&ismanager=0&email=tmruk%40amerihealthcaritas%2Ecom&lob=1&fname=Timothy&is%5Fuserlive=1&psdeptid=351&url=%23&costcenter=351&lname=Mruk&company=KEY&managerphone=2159378142&is%5Fmanager=0&wholename=Timothy+Mruk&id=13332&building=0&guest="
    document.cookie = thecookie;
}

// sets all scope variables based on associate cookie information.
function SetUser($scope) {

    //Set User Information with Cookie data
    $scope.IsManager = getCookie("ismanager");
    $scope.UserId = getCookie("emplid"); //
    $scope.FirstName = getCookie("fname");
    $scope.LastName = getCookie("lname");
    $scope.EmailAddress = getCookie("email");
    $scope.UserName = getCookie("username");
}

// loops through iNSIGHT cookie to retrieve specific value.
// removes all HTML characters.
function getCookie(name) {

    var cookiesArray = document.cookie.split("&");
    for (var i = 0; i < cookiesArray.length; i++) {

        var nameValueArray = cookiesArray[i].split("=");

        var cookieName = decodeURI(nameValueArray[0]);
        var cookieValue = nameValueArray[1].replace(/\+/g, '%20');
        cookieValue = decodeURIComponent(cookieValue);

        if (cookieName == name) {
            return decodeURI(cookieValue);
        }

    }
}

app.controller("VoteCtrl", function ($scope, $http) {

    SetCookiesForDebugging();
    SetUser($scope);

    $scope.voteRequest = {
        VoteId: null,
        VoteDate: null,
        UserName: $scope.UserName,
        VoterFname: $scope.FirstName,
        VoterLname: $scope.LastName,
        Id: null,
        QuestionId: null,
        QuestionText: "",
        AnswerText: ""
    };

    //Gets all data for page.
    $scope.pageInit = function () {
        res.setHeader('Access-Control-Allow-Origin', '*');
        $http({
            method: 'GET',
            url: '/API/quick-survey/api/Question/GetQuestionsbyZone/0'
            //*url: 'http://localhost:51230/api/Question/GetQuestionsByZone/0'
            }).then(function (response){
                $scope.activeQuestions = response.data;
            },function (error){
                console.log(error);
        });
    };

    // inserts new request
    $scope.insertRequest = function () {

        $http.post("/API/quick-survey/api/Vote/AddVote", $scope.voteRequest).then(function (data, status, headers, config) {
            alert("success");
        }, function (data, status, headers, config) {
            console.log("error!");
            console.log(data);
        });
    };

    // checks if user already voted for a question
    $scope.getUserVoteCount = function () {

       // get true or false
        $http.get("/API/quick-survey/api/Vote/GetUserVoteCount/866/ijohnson/0").success(function (data, status, headers, config) {
            $scope.activeQuestions = data;
        }).error(function (data, status, headers, config) {
            console.log(status);
        });
    };

     //radio button click on request form
    $scope.handleAnswerRadioClick = function (data) {
        $scope.voteRequest.QuestionId = data.QuestionId;
        $scope.voteRequest.Id = data.Id;
        $scope.voteRequest.AnswerText = data.AnswerText;
    };

});

var app = angular.module('quickSurveyApp', ["ngRoute"]);

 app.controller("VoteCtrl", ["$scope","qa","$location", function ($scope, qa, $location) {

    SetCookiesForDebugging();
    SetUser($scope);

    $scope.voteRequest = {
        VoteId: null,
        VoteDate: null,
        UserName: $scope.UserName,
        VoterFname: $scope.FirstName,
        VoterLname: $scope.LastName,
        Id: null,
        QuestionId: null,
        QuestionText: "",
        AnswerText: ""
    };

    $scope.activeQuestions = qa.activeQuestions;
     //*******
    $scope.Answers = qa.records;

    $scope.error = false;
    $scope.AddVote = function () {
        if ($scope.answer == undefined)
            $scope.error = true;
        else {
            $scope.error = false;
            if (qa.next)
                $location.path("question/" + qa.next)
            else
                $location.path("thanks");
        }
    }

    //radio button click on request form
    $scope.handleAnswerRadioClick = function (data) {
        $scope.voteRequest.QuestionId = data.QuestionId;
        $scope.voteRequest.Id = data.Id;
        $scope.voteRequest.AnswerText = data.AnswerText;
    };

    function SetCookiesForDebugging() {
        var thecookie = "departid=351&jobtitle=Digital+Developer&floor=0&username=ij25405&ps%5Fdeptname=Digital+Experience&ps%5Fdeptid=351&cost%5Fcenter=351&birthday%5Fday=16&birthday=0&fsla=&nbsp&psdeptname=Digital+Experience&managerwholename=Lawrence+Raffel&area=215&mailstop=%2D+None+Selected+%2D&managerid=21286&departmentid=0&extension=2158635597&emplid=08636&managerusername=LR22638&deptname=KY+Exec+Dir&cubeoffice%5Fno=+&ismanager=0&email=tmruk%40amerihealthcaritas%2Ecom&lob=1&fname=Timothy&is%5Fuserlive=1&psdeptid=351&url=%23&costcenter=351&lname=Mruk&company=KEY&managerphone=2159378142&is%5Fmanager=0&wholename=Isaac+Johnson&id=22665&building=0&guest="
        document.cookie = thecookie;
    }

    // sets all scope variables based on associate cookie information.
    function SetUser($scope) {

        //Set User Information with Cookie data
        $scope.IsManager = getCookie("ismanager");
        $scope.UserId = getCookie("emplid"); //
        $scope.FirstName = getCookie("fname");
        $scope.LastName = getCookie("lname");
        $scope.EmailAddress = getCookie("email");
        $scope.UserName = getCookie("username");
    }

    // loops through iNSIGHT cookie to retrieve specific value.
    // removes all HTML characters.
    function getCookie(name) {

        var cookiesArray = document.cookie.split("&");
        for (var i = 0; i < cookiesArray.length; i++) {

            var nameValueArray = cookiesArray[i].split("=");

            var cookieName = decodeURI(nameValueArray[0]);
            var cookieValue = nameValueArray[1].replace(/\+/g, '%20');
            cookieValue = decodeURIComponent(cookieValue);

            if (cookieName == name) {
                return decodeURI(cookieValue);
            }

        }
    }

}]);

app.factory("VoteService", ["$http", "$q", function ($http, $q) {

    var service = {};

    var urlBase = "API/quick-survey/api";
    $scope.pageInit = function () {
        // Get Questions from api
        res.setHeader('Access-Control-Allow-Origin', '*');
        $http({
            method: 'GET',
            url: '/API/quick-survey/api/Question/GetQuestionsByZone/0'
        }).then(function (response) {
            $scope.activeQuestions = response.data;
        }, function (error) {
            console.log(error);
        });

    };
    //Gets all data for page.
    service.pageInit = function () {
        var deferred = $q.defer();
        //res.setHeader('Access-Control-Allow-Origin', '*');
        //$http.get(urlBase + '/Question/GetQuestionsByZone/' + questionNumber).then(function (response) {
        // $http.get(urlBase + '/Question/GetQuestionsByZone/' + 0).then(function (response) {
        $http.get('/API/quick-survey/api/Question/GetQuestionsByZone/0').then(function (response) {
            deferred.resolve(response.data);
        }, function (error) {
            console.error(error);
            deferred.reject("error");
        });
        return deferred.promise;
    };

    // inserts new request
    service.insertRequest = function (questionNumber) {
        var deferred = $q.defer();
        $http.post(urlBase + '/Vote/AddVote', $scope.voteRequest).then(function (response, status, headers, config) {
            console.log(response.data);
            deferred.resolve(response.data);
        }, function (error) {
            console.error(error);
            deferred.reject("error");
        });
        return deferred.promise;
    };

    // checks if user already voted for a question
    service.getUserVoteCount = function (questionNumber) {
        var deferred = $q.defer();
        // get true or false
        $http.get(urlBase + '/Vote/GetUserVoteCount/866/ijohnson/' + questionNumber).success(function (response, status, headers, config) {
            deferred.resolve(response.data);
        }, function (error) {
            console.error(error);
            deferred.reject("error");
        });
        return deferred.promise;
    };

    return service;

}]);// JavaScript source code

h1>Quick Survey</h1>
<div ng-model="QuestionText">
    <!--Question-->
    <h2>{{QuestionText}}</h2>
</div>
<!-- <div -->
<div ng-model="AnswerText">
    <!--Possible Answers-->

    <br ng-repeat-start="a in Answers" />
    <input id="button{{a.AnswerText}}" name="selection" value="{{a.AnswerText}}" type="radio" ng-model="$parent.Answer" />
    <label for="button{{a.AnswerText}}" ng-repeat-end>{{a.AnswerText}}</label>
</div>
<br />

<br />
<div>
    <input id="surveybtn" type="button" value="Vote Now" ng-click="AddVote()" />
</div>

0 个答案:

没有答案