Angular.js——在作用域中使用函数的优雅方式

Angular.js - elegant way to use functions in scope

本文关键字:函数 方式 js 作用域 Angular      更新时间:2023-09-26

我计划在整个应用程序中运行各种计算以显示不同的消息/类,我不确定在Angular中最优雅/最佳实践的方法是什么。

下面是我试图实现的一个简单示例,尽管我的计划是创建更复杂的表达式,这些表达式对我来说在标记中没有意义。

<li ng-repeat="goal in goals"> 
<strong ng-show="((goal.count / goal.goalNumber) * 100) == 0"> Get to work</strong>
<strong ng-show="((goal.count / goal.goalNumber) * 100) == 50"> Half way there!</strong>
<strong ng-show="((goal.count / goal.goalNumber) * 100) == 100"> Success!!</strong>
</li>

有人能推荐一个更模块化/可重用的方法来做到这一点吗?我想有一种方法是创建一个可以在整个模板中使用的函数。但是我如何得到每个"目标"迭代的目标呢?计数并进球。函数中的goalNumber ?这是我从控制器调用的东西,还是一个指令是存储它的更好的地方?

多谢。

稍微改进一下…

HTML

<li ng-repeat="goal in goals">  
    <strong ng-show="geq(goal, 0)"> Get to work</strong>
    <strong ng-show="geq(goal, 50)"> Half way there!</strong>
    <strong ng-show="geq(goal, 100)"> Success!!</strong>
</li>

JS

$scope.geq = function(g, n){
   return ((100 * g.count / g.goalNumber ) === n);
};

Markup

<li ng-repeat="goal in goals"> 
<strong ng-show="zeroGoals($index)"> Get to work</strong>
<strong ng-show="fiftyGoals($index)"> Half way there!</strong>
<strong ng-show="oneHundredGoals($index)"> Success!!</strong>
</li>

Js

$scope.zeroGoals = function(index){
       return (($scope.goals[index].count / $scope.goals[index].goalNumber) * 100) == 0;
};
$scope.fiftyGoals = function(index){
       return (($scope.goals[index].count / $scope.goals[index].goalNumber) * 100) == 50;
};
$scope.oneHundredGoals = function(index){
       return (($scope.goals[index].count / $scope.goals[index].goalNumber) * 100) == 100;
};

ng-repeat所在的元素添加控制器。该控制器将有权访问循环变量。例子:

视图

<div ng-app="app" ng-controller="Controller">
    <div ng-repeat="item in items" ng-controller="RepeatController">
        {{item}}: {{doubleItem()}}
    </div>
</div>
控制器

angular.module('app', [])
.controller('Controller', function ($scope) {
    $scope.items = [1, 2, 3, 4];
})
.controller('RepeatController', function ($scope) {  
    $scope.doubleItem = function () { 
        return $scope.item * 2; 
    };
})

在视图中使用如下过滤器:

 <strong ng-if="'goal.count ¦ isGoal : goal.goalNumber : 50">

和过滤器:

 app.filters('isGoal', function() {
     return function(count, goalNumber, reached) {
         return (count / goalNumber) == reached;
     }
 });