1

在谈论 angularjs 中的声明性语法时,我们通常会提到指令,以及我们如何将$scope属性传递到这些指令中以进行处理、DOM 操作、数据收集以及可能的各种组合。

但是,目前我正在努力说服我的团队(更不用说我自己)声明性模板是正确的方法。这并不一定意味着使用指令,而是如何使用指令。

以下控制器/模板对显示了一个示例,其中我根据“模型”/$scope 的属性显示一个元素。

function MainController($scope) {
    $scope.hasJQuery = true;

    $scope.hasProblems = true;

    $scope.hasLodash = false;

    $scope.hasStuff = true;
}

<div ng-controller="MainController">
    <span ng-if="hasJquery && hasProblems && hasLodash && hasStuff">TL;DR?</span>
<div>

但另一种方法可能看起来像这样

function MainController2($scope) {
    // Get/Retrieve $scope stuff...

    // Setup "ViewModel" Data
    $scope.hasJQueryAndProblemsAndLodashAndStuff = $scope.hasJQuery && $scope.hasProblems && $scope.hasLodash && $scope.hasStuff;

    $scope.hasJQueryAndLodash = $scope.hasJQuery && $scope.hasLodash;
}

<div ng-controller="MainController">
    <span ng-if="hasJQueryAndProblemsAndLodashAndStuff">...</span>
    <span ng-class="hasJqueryAndLodash ? 'blue' : ''"></span>
</div>

该名称是可能的夸张版本,isReadyhasAll重点是表明有时 html 需要多个ng-class属性,而各种逻辑将依赖于$scope属性。

我主要看到第一个例子是人们通常使用的——除非逻辑变得非常复杂。另外,我也知道 angularjs 是一个 MVW,但这对我没有帮助。

有时我应该只$scope在控制器中添加“ViewModel”(表示逻辑)吗?每时每刻?绝不?将表示逻辑放入控制器/模板的优点/缺点是什么?

4

0 回答 0