13
 <div data-ng-controller="maincontrol">
   <div class="main">
   </div>
  <button data-ng-click="submit()">click</button>
 </div>

クリックボタンをクリックすると、メイン div 内に 1 つの div を追加します。クリックごとに(動的に)1つの新しいdivを追加したい.また、子divが存在するかどうかを調べたい.

私はjqueryでこのようにします

$('main').append();

append(); 内で div を渡します。

しかし、 angular..js を使用して行う方法は?

4

2 に答える 2

25

Using a directive could be a solution, but it's still too close to jQuery. When you play with Angular, you have to think differently.

jQuery is procedural.

1- I am finding an element in the dom

2- I am doing some stuff

3- I am adding, removing, updating elements in the dom

angular is declarative

  • You define your data

  • You define how your data should be displayed (using ng-repeat, ng-class, etc..)

then..

  • when you are playing with your data, the view is automatically updating.

If you want to play correctly with angular you should maybe do something like:

Template:

 <div class="main">
    <div ng-repeat="stuff in stuffs"><h1>{{stuff.title}}</h1> <p>{{stuff.content}}</p></div>
 </div>

Controller:

function MainCtrl() {
    $scope.stuffs = [];
    $scope.submit = function() {
       $scope.stuffs.push({title: 'Hello', content: 'world'});
    }
}
于 2013-10-29T12:37:15.007 に答える
15

一般的には、DOM 操作用のディレクティブを作成するのが最善です (ディレクティブは他の多くの用途にも使用されます)。

ディレクティブ内では、angular.element. ページで angular.js の前に jQuery がインストールされている場合、これは jQuery オブジェクトであり、それ以外の場合は、jqLite多くの jQuery 互換メソッドを持つオブジェクトです。

非常に簡単な例:

 <button data-ng-click="submit()" my-directive>click</button>
app.directive('myDirective',function(){
     return function(scope, element, attrs){
          element.click(function(){
               element.parent().find('.main').append('<div>Some text</div>')
           })
      }
})

ディレクティブを読み、angular.element

于 2013-10-29T12:25:14.250 に答える