2

我刚刚开始,angular.js今天我正在编写我的控制器:

myApp.controller('RepetitionController', ['$scope', '$location', 'repetitionService',
    function ($scope, $location, repetitionService) {



        $scope.questions = repetitionService.getQuestions();
        $scope.questionsLeft = $scope.questions.length;
        $scope.questionsAnswered = 0;
        $scope.percentageLeft = ($scope.questionsLeft == 0 ? 100 : 0);
        $scope.repetitonState = ??? 
        $scope.endRepetition = function () {
            repetitionService.clearSelectedSets();
            $location.path("/setsAndCollections");
        }

        $scope.submitAnswer = function () {
            alert("alert");
        }
    }]);

我开始怀疑。

你可以看到我使用三元运算符来创建初始状态$scope,现在在我的repetitionState领域中我想要这样的东西(questionsLeft === 0 ? 'finished' : questions[0].type)

有什么方法可以定义一个在填充$scope对象后调用的函数,某种后构造函数?

或者也许有一种方法可以“观察”函数,所以我可以写

$scope.repetitionState = function(){
    ///logic here
};

我只是担心在某些情况下我需要编写logicalExpression ? anonymousFunction () : someOtherAnonymousFunction(),对我来说,嵌套所有这些匿名函数(目前)有点难以阅读,我想知道其中的某些部分angular是否有用在这种情况下。

4

2 回答 2

4

您当然可以观看功能。$watchwatchExpression 参数接受字符串或函数。如果您使用的是函数,则当前作用域将作为第一个参数传递给该函数。

要记住的重要一点是 watchExpression 函数应该是幂等的,因此请确保您只更新侦听器函数中的范围。

$scope.repititionState = getRepititionState($scope);

$scope.$watch(getRepititionState, function(newVal, oldVal, scope) {
    scope.renditionState = newVal;
});

function getRepititionState(scope) {
    var repititionState;
    // your logic here, just remember to set and return repititionState
    return repititionState;
}
于 2013-04-06T22:25:59.953 回答
1

无论您想在哪里引用,repititionState为什么不将其作为函数引用?

例如:让我们假设您将使用repititionState以下课程为您提供课程

<div ng-class="repititionState"></div>

$scope.repititionState = ($scope.questionsLeft === 0 ? 'finished' : $scope.questions[0].type)

这样,每当您的问题完成时, div 就会获得一个finished. 为了使它repititionState依赖于另一个变量(就像你想要的那样),它就像使它成为一个函数一样简单。

<div ng-class="repititionState()"></div>

()注意现在将 标记repititionState为函数的额外内容。

$scope.repititionState = function(){
    return ($scope.questionsLeft === 0 ? 'finished' : $scope.questions[0].type);
}

如果你在 anng-repeat那么你甚至可以通过$index使这个函数更通用。

$scope.repititionState = function($index){
return ($scope.questionsLeft === 0 ? 'finished' : $scope.questions[$index].type);
}

这通常在其他框架中称为计算属性。在 Angular 中,它只是一个函数。希望这可以帮助。

于 2013-04-06T23:01:40.350 回答