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.

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that provided the exact help I needed. The post link you referenced is also a big help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.