簡體   English   中英

如何從Math表達式和另一個范圍var更新范圍var?

[英]How to update scope var from Math expression and another scope var?

不知道我是否想清楚我的問題,但是我真正想要的是用ng-repeat每個<li>ng-style更新min-width ,以等於100 / array.length的百分比。

我的第一個解決方案是:

<li ng-style="{'min-width': (100 / array.length) + '%'}">

這可行,但是我不喜歡視圖中的Math表達式,而是希望將其放在控制器中。 符合以下條件的東西:

$scope.percentage = (100 / $scope.array.length) + '%'

<li ng-style="{'min-width': percentage}"

這種方法的問題在於,當數組內容更改時, percentage不會更改。 我可以在array添加$watchCollection並在那里更新percentage ,但是感覺不對,就像我缺少一種更好的方法一樣。 是嗎

如果沒有,您更喜歡哪種解決方案? 視圖中的數學表達式,或$watchCollection

您應使用一個函數作為示例:

$scope.getTableWidth = function(){
   return (100 / $scope.array.length) + '%';
}

<li ng-style="{'min-width': getTableWidth()}">

因此,在每次DOM刷新時,即使數組長度發生變化,您的數組長度也會刷新。

問候,

如果使用函數代替:

$scope.percentage = function () {
  return (100 / $scope.array.length) + '%';
}

// or give array as parameter

$scope.percentage = function (array) {
  return (100 / array.length) + '%';
}

然后使用它:

<li ng-style="{'min-width': percentage()}">

Or

<li ng-style="{'min-width': percentage(array)}">

還有另一種方法是使用過濾器:

// here it's presumed that you have 
//     var app = angular.module(...);
// somewhere above
app.filter('widthPercentage', function () {
    return function (items) {
        return 100 / items.length + '%';
    };
});

並使用它

<li ng-style="{'min-width': (array | widthPercentage)}">

您應該將百分比定義為函數。

看這里:

http://jsfiddle.net/waxolunist/5bnhj4vt/6/

HTML:

<div ng-app="app">
    <div ng-controller="AController">
        <ul>
            <li class="red" ng-repeat="item in items" ng-style="{'width': percentage()}">{{item}}</li>
        </ul>

    <button ng-click="addItem()">addItem</button>
    </div>


</div>

JS

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

app.controller('AController', function($scope) {

    $scope.items = [1,2,3,4,5,6];

    $scope.percentage = function() {
        return 100/$scope.items.length + '%';
    }

    $scope.addItem = function() {
        $scope.items.push($scope.items.length + 1);
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM