【问题标题】:Replace $scope with "'controller' as" syntax将 $scope 替换为 "'controller' as" 语法
【发布时间】:2014-10-13 20:37:57
【问题描述】:

我正在关注这个 AngularJS+ASP.NET 教程(http://www.asp.net/web-api/tutorials/hands-on-labs/build-a-single-page-application-(spa)-with-aspnet-web-api-and-angularjs),他们使用了 $scope,但我试图用新的语法“控制器”替换它。 (检查AngularJs "controller as" syntax - clarification?后)

我所做的目前不起作用,因为页面在 nextQuestion() 函数中调用了 $http.get,但视图保持不变,只是标题为“正在加载问题...”

我的代码:

JS http://pastebin.com/RfngRuZD

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

app.controller('QuizCtrl', ['$http', function ($http) {
    this.answered = false;
    this.title = "loading question...";
    this.options = [];
    this.correctAnswer = false;
    this.working = false;

    this.answer = function () {
        return this.correctAnswer ? 'correct' : 'incorrect';
    };

    // GET
    this.nextQuestion = function () {
        this.working = true;
        this.answered = false;
        this.title = "loading question...";
        this.options = [];

        $http.get('/api/trivia').success(function (data, status, headers, config) {
            this.options = data.options;
            this.title = data.title;
            this.answered = false;
            this.working = false;
        }).error(function (data, status, headers, config) {
            this.title = "Oops... something went wrong.";
            this.working = false;
        });
    };

    // POST
    this.sendAnswer = function (option) {
        this.working = true;
        this.answered = true;

        $http.post('/api/trivia', { 'questionId': option.questionId, 'optionId': option.id }).success(function (data, status, headers, config) {
            this.correctAnswer = (data === "true");
            this.working = false;
        }).error(function (data, status, headers, config) {
            this.title = "Oops... something went wrong.";
            this.working = false;
        });
    };
}]);

Index.cshtml http://pastebin.com/YmV1hwcU

@{
    ViewBag.Title = "Play";
}

<div id="bodyContainer" ng-app="QuizApp">
    <section id="content">
        <div class="container">
            <div class="row">
                <div class="flip-container text-center col-md-12" ng-controller="QuizCtrl as quiz" ng-init="quiz.nextQuestion()">
                    <div class="back" ng-class="{flip: quiz.answered, correct: quiz.correctAnswer, incorrect: !quiz.correctAnswer}">

                    <p class="lead">{{quiz.answer()}}</p>
                    <p>
                        <button class="btn btn-info btn-lg next option" ng-click="quiz.nextQuestion()" ng-disabled="quiz.working">Next Question</button>
                    </p>
                </div>
                    <div class="front" ng-class="{flip: quiz.answered}">
                        <p class="lead">{{quiz.title}}</p>
                        <div class="row text-center">
                            <button class="btn btn-info btn-lg option"
                                ng-repeat="option in quiz.options" ng-click="quiz.sendAnswer(option)" ng-disabled="quiz.working">
                                {{option.title}}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

@section scripts{
    @Scripts.Render("~/Scripts/angular.js")
    @Scripts.Render("~/Scripts/app/quiz-controller.js")
}

【问题讨论】:

    标签: javascript asp.net angularjs controller angularjs-scope


    【解决方案1】:

    您基本上找到了在控制器中使用this 不是一个好主意的原因。 $http 的成功承诺中的this 不是控制器的this,因为此函数在不同的上下文中执行。如果您通过闭包获得$scope,这将不是问题。

    您可以通过定义变量var that = this; 来解决此问题,然后改用that。

    【讨论】:

    • 谢谢,我知道这是一个简单的问题,但有点令人困惑。在阅读了 johnpapa 的文章后,我认为新语法可以提供很多东西。
    【解决方案2】:

    或者您可以只使用 javascripts 绑定函数并传入您要使用的正确 this。

    $http.get('/api/trivia').success(function (data, status, headers, config) {
        this.options = data.options;
        this.title = data.title;
        this.answered = false;
        this.working = false;
    }.bind(this));
    

    【讨论】:

    • 好主意,但是如果你需要同时引用这两个,那就行不通了。
    【解决方案3】:

    这对我有用,谢谢o/

    //form.blade.php

    <md-content flex ng-controller="EmployeeController as child" ng-cloak>
     <md-input-container>
        <label>State</label>
        <md-select name="fk_state" ng-model="form.fk_state">
            <md-option><em>Select</em></md-option>
            <md-option ng-repeat="state in child.states" ng-value="state.uf">
                [[state.uf]]
            </md-option>
        </md-select>
     </md-input-container>
    </md-content>
    

    //employeeController.js

    angular.module("app").controller('EmployeeController',
     function($scope, $q, utilsFactory){
    
        var that = this;
    
        //service that contains a $http request
        utilsFactory.getAll('states').then(function(response) {
            that.states = response.data;
            console.log(that.states); //should be available to child.states
        });
     }
    )
    

    【讨论】:

      猜你喜欢
      • 2015-01-26
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      相关资源
      最近更新 更多