在angularJS

时间:2016-10-26 11:10:47

标签: javascript angularjs

对不起,也许这是一个愚蠢的问题,但我还在学习。

我想在我的视图中点击按钮动态添加一些元素。对我来说工作正常,但我有一些疑惑。因为我正在学习angularJs我想知道有更好的方法来做这些事情。

1.从文档我理解angularJS与jquery完全不同所以在这个例子中我使用了与jquery一起使用的相同概念,所以我想知道是否有更好的方法来做到这一点。

2.i可以使用控制器中的$ element访问dom元素,但无法访问相同的内部点击事件

app.controller('SalesController',function($scope,$element) {
  //here we can access like this
  $element[0].getElementsByClassName("classSub")[0];
  $scope.Change = function () {
    //we can access variables like this
    var temp= $scope.salesData
    //but this code will not work here
    $element[0].getElementsByClassName("classSub")[0];      
  }
});

3.innerHTML和append不能与getElementsByClassName一起使用,但它可以与document.querySelector一起使用

$scope.Change = function () {
  if($scope.salesData%2==0) {
    bindChart="";
    bindChart=bindChart+"<div class='sub1'></div>";    

    //these code will not add the div dynamically
    //document.getElementsByClassName("classSub"[0].innerHTML=bindChart;
    //document.getElementsByClassName("classSub")[0].append(bindChart);
    //document.querySelector( '.classSub' ).append(bindChart);

    //this will work
    document.querySelector( '.classSub' ).innerHTML=bindChart;
  } else {
    bindChart="";
    bindChart=bindChart+"<div class='sub2'></div>";
    document.querySelector( '.classSub' ).innerHTML=bindChart;
  } 
  $scope.salesData++;
}  

任何人都可以解释问题是什么......我是angularJS的初学者

Fiddler

1 个答案:

答案 0 :(得分:0)

我已从你的评论中更新了我的答案:

只需在控制器中声明$scope.salesData = [];,然后在HTML中使用此代码:

<div ng-repeat="sale in salesData" ng-class="{sub1: sale.n == 0, sub2: sale.n == 1}"></div>
<button type="button" ng-click="salesData.push({n:salesData.length % 2})">Click Me!</button>     

当您点击按钮时,它会根据您的情况(奇数或偶数)创建新的div

分叉你的小提琴here

它是如何工作的?

  • $scope.salesData是一个空数组。
  • 当您点击该按钮时,它会在salesData。{/ li>中推送一个对象
  • 此对象作为值(n)在0和1之间切换(奇数/偶数)。
  • ng-repeat会为此数组中的每个元素创建一个div
  • ng-class将根据n值(奇数/偶数)设置此div的样式。