Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AngularJS项目选择和DOM操作_Angularjs - Fatal编程技术网

AngularJS项目选择和DOM操作

AngularJS项目选择和DOM操作,angularjs,Angularjs,我有一个从JSON填充的项目列表,然后我需要选择它们的值并填充另一个选定项目列表,但是,如果特定项目已经被选中,请再添加一个项目进行计数 app.controller("NewPizza", function($scope, ingredients) { $scope.selectedIngredients = []; ingredients.get().then(function(response){ $scope.ingredients = response.data;

我有一个从JSON填充的项目列表,然后我需要选择它们的值并填充另一个选定项目列表,但是,如果特定项目已经被选中,请再添加一个项目进行计数

app.controller("NewPizza", function($scope, ingredients) {
  $scope.selectedIngredients = [];

  ingredients.get().then(function(response){
    $scope.ingredients = response.data;
  });

  function _ingredientExist(id) {
    return $scope.selectedIngredients.some(function(el) {
        return el._id === id;
    });
  }

   function _addMore(selectedIngredient) {
    console.log(selectedIngredient)
  }

$scope.addIngredient = function(selectedIngredient) {
    if($scope.selectedIngredients.length == 0) {
        $scope.selectedIngredients.push(selectedIngredient);
    }else{
        if(_ingredientExist(selectedIngredient._id)) {
            _addMore(selectedIngredient._id);
            return false;
        }
        $scope.selectedIngredients.push(selectedIngredient);
    }
};

});
结果应该是这样的

要选择的项目

干酪 培根 火腿

选定的项目

2奶酪,以防用户多次选择奶酪 培根

HTML

问题是,我不知道如何准确地实现此功能,因为在控制器内部,DOM操作被认为是一种不好的做法,但是如果我发出指令来处理,我不知道如何正确地填充$scope.selectedIngredients


谢谢

一种方法是,您可以向items模型添加计数,然后复制该模型并增加该数字

创建了一个小提琴:

JS

HTML


您是对的,在角度世界中从控制器更新DOM被认为是错误的

这样做的原因是,如果您更新数据(例如,SelectedGredients数组),您不需要为您更新DOM

实现这一点的一种方法是跟踪每种成分的数量以及添加的成分。您可以在不接触从服务器返回的json的情况下执行此操作

然后,当您更改计数时,angular将为您更新DOM

下面是一个例子:

HTML

JS

     <div class="">
<h1>New Pizza</h1>
<input ng-model="name"/>
<a>Save pizza</a>
<ul >
    <li class="selectIngredients" ng-repeat="ingredient in ingredients" ng-click="addIngredient(ingredient)" id="{{ingredient._id}}">
        {{ingredient.name}}
    </li>
</ul>
    <ul ng-model="selectedIngredients">
        <li data-id="{{selectedIngredient._id}}" ng-repeat="selectedIngredient in selectedIngredients track by $index">
            <span>1</span> {{selectedIngredient.name}}
        </li>
    </ul>
</div>
var app = angular.module('itemsApp',[]);

app.controller('ItemsCtrl',function($scope) {
    $scope.items = [
        {name:'Cheese',num:0},
        {name:'Bacon',num:0},
        {name:'Ham',num:0}
    ];

    $scope.my_items = angular.copy($scope.items);

    $scope.addItem = function(item) {
        var idx = $scope.items.indexOf(item);
        var num = $scope.my_items[idx].num;
        $scope.my_items[idx].num = num + 1;
    };

    $scope.removeItem = function(my_item) {
        var idx = $scope.my_items.indexOf(my_item);
        var num = my_item.num;

        if (num > 0) {
            $scope.my_items[idx].num = num -1;
        }
    };
});
<div ng-app="itemsApp" ng-controller="ItemsCtrl">
    <h4>Available Items</h4>
    <table>
        <tr ng-repeat="i in items">
            <td>{{i.name}}</td>
            <td><button ng-click="addItem(i)">+</button></td>
        </tr>
    </table>
    <hr>
    <h4>My Items</h4>
    <table>
        <tr ng-repeat="i in my_items" ng-show="i.num > 0">
            <td>{{i.name}} ({{i.num}})</td>
            <td><button ng-click="removeItem(i)">Remove 1</button></td>
        </tr>
    </table>
</div>
<!DOCTYPE html>
<html ng-app="test">

  <head>
    <script data-require="angular.js@1.3.0-beta.5" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="PizzaCtrl">
  <h4>Toppings</h4>
    <ul>
      <li ng-repeat="i in ingredients">
        {{i.name}} - <a href ng-click="addIngredient(i)">Add</a>
      </li>
    </ul>
    <h4>Selected Toppings</h4>
    <ul>
      <li ng-repeat="t in toppings">
       {{t.ingredient.name}}
       <span ng-if="t.count > 1">
         x{{t.count}}
       </span>
       <a href ng-click="removeTopping(t, $index)">Remove</a>
      </li>
    </ul>
  </body>

</html>
angular.module('test', [])
.controller('PizzaCtrl', function($scope) {
  /* let's protend we called ingredients.get() here */
  $scope.ingredients = [
    { name: 'Cheese', id: 1 },
    { name: 'Bacon',  id: 2 },
    { name: 'Ham',    id: 3  }
  ];

  /* this will hold both an Ingredient and a Count */
  $scope.toppings = [];

  /* Check if the ingredient already exists in toppings[], and if so,
   * return it. */
  function findTopping(ingredient) {
    for(var i = 0; i < $scope.toppings.length; ++i) {
      if ($scope.toppings[i].ingredient.id == ingredient.id) {
        return $scope.toppings[i];
      }
    }
    return null;
  }

  /* If the ingredient is already there, increment it's count,
   * otherwise add it. */
  $scope.addIngredient = function(ingredient) {
    var t = findTopping(ingredient);
    if (t) {
      t.count++; 
    } else {
      $scope.toppings.push({ingredient: ingredient, count: 1});
    }
  };

  /* Opposite of the above! */
  $scope.removeTopping = function(t, index) {
      if (t.count > 1) {
        t.count--;
      } else {
        $scope.toppings.splice(index, 1);
      }
  };
})