3

I'm just learning angularjs and have something working mixing jQuery with the angularjs. I know this isn't the correct way, but I don't know what is the Angularjs correct way to do this.

In the HTML I have this tag which is just a button to add the div tag dynamically onto the page.

<div ng-controller="pgCtrl">
    <button id="new-btn" ng-click="newDiv()">Gimme a div!</button>
</div>

In the javascript I have this:

app.controller('pgCtrl', function($scope){
    $scope.newDiv = function(){
        // Load an element that uses controller anotherCtrl
        $('<div class="blah" ng-controller="anotherCtrl">' +
            '<button id="another-btn" ng-click="stuff()">-</button>{{stuff}}' +
            '</div>').appendTo('body');
        angular.bootstrap($('.blah'), ['app']);
    };
});

I know this isn't the "proper" way to do this with Angularjs. I'm mixing in vary basic jQuery and it works, but I'm not learning anything doing this.

padawanlvn
  • 399
  • 1
  • 4
  • 12

1 Answers1

6

Using angular always think about updating a scope object first ( the Model ). In markup (the View) you then have numerous ng built in directives to handle processing scope objects.

In fact when you start with angular, it's almost best not to even include jQuery in page. It helps force you to stay away from jQuery DOM manipulation methodology and start thinking Model/Controller /View

This post is a must read for anyone migrationg from jQuery to angular: How do I “think in AngularJS” if I have a jQuery background?

A simple starter for your demo would be:

app.controller('pgCtrl', function($scope){
      $scope.items=[];
      $scope.newDiv=function(){
           $scope.items.push( {stuff: 'Some stuff text'}
      }
})

Then in the view will use ng-repeat so you can clcik your button as many times as you want and keep adding stuff

<div ng-repeat="item in items" >
        <div class="blah" ng-controller="anotherCtrl">
            <button id="another-btn" ng-click="stuff()">-</button>{{item.stuff}}
         </div>

</div>
Community
  • 1
  • 1
charlietfl
  • 170,828
  • 13
  • 121
  • 150