2

Someone created custom tag in the project, such as

<mytable config='{head:[title1, title2],data:[[col1, col2]]}'></mytable> ,

the tag above will generate a table after the page is loaded.

I want to create a button in the table, then I insert the string :

'<button class="btn btn-primary" ng-click="lookup(3)">lookup</button>';

but the ng-click doesn't work. I write a simple code to mock it:

<!DOCTYPE html>
<html ng-app="myApp">
    <head>
        <script type="text/javascript" src="/javascripts/jquery.min.js"></script>
        <script type="text/javascript" src="/javascripts/angular/1.4.0/angular.min.js"></script>
        <script>
            var create = function () {
                $('#template').html('<button ng-click="changeName()">click me</button>')
            }
        </script>
    </head>
    <body ng-controller="myCtrl">
        <span>{{name}}</span>
        <div id="template"></div>
        <button onclick="create()">create</button>

        <script>
            var app = angular.module('myApp', []);
            app.controller('myCtrl', function($scope) {
                $scope.name = "John";
                $scope.changeName = function () {
                    $scope.name = "Jack";
                    alert("success");
                }
            });
        </script>
    </body>
</html>

I have googled and find the angular should compile the newly created element, but I don't know how to in this situation

2 Answers 2

2

You need the $compile service.

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $compile) {

        $scope.create = function () {
               $compile($('#template').html('<button ng-click="changeName()">click me</button>'))($scope);
        }
               $scope.name = "John";
               $scope.changeName = function () {
                  $scope.name = "Jack";
                  alert("success");
               }
     });

And change your html to

<button ng-click="create()">create</button>

Or you can get all body and then call $compile to it

var body = $angular.element(document).find('body');
$compile(body)($scope);
Sign up to request clarification or add additional context in comments.

1 Comment

As I mentioned, the table only need json format config, maybe after jquery's ready() event that it will create the table, the solution you provided doesn't help
0

You should use ng-repeat to create those buttons, not jQuery.

And then angular would automatically bind ng- to this new element.

1 Comment

the tag <mytable> contains other features that I need, there is no need to create those features again, so I can't use ng-repeat to create a new table

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.