Kuan
Kuan

Reputation: 11389

How to bind data model in directive and set event handler correctly

All:

Currently, what my directive code looks is pretty simple:

    <div ng-controller='main'>
        <dirtest></dirtest>
        <dirtest></dirtest>
    </div>

<script>
     var app = angular.module("vp", []);
        app.controller("main", function($scope){
            $scope.name="init name";
        })

        app.directive("dirtest", function($compile){
            return {
                restrict: "E",
                scope: false,
                controller : function($scope){
                },
                compile: function(tEl, tAttrs){
                    return {
                        post: function(scope, el, attrs, ctrl){
                            el.append($compile("<button class='dirbtn'>{{name}}</button>")(scope));
                            $("button.dirbtn").on("click", function(){
                                scope.name = Math.random();
                                console.log(scope.name);
                                scope.$apply();
                            });
                        }
                    };
                }
            }
        });
</script>

what this code supposed to do is: Click any button, change all the buttons text.

First question: Rather than using $compile to compile hard coded scope data model {{name}}, is there a way that I can programmatically do the data binding to dynamically added DOM?

Second question: When I added two dirtest directives to page, one wierd thing is the clicking on first button will call its post link function twice(we can tell from the console, there are two numbers generated when I clicked the first button) while the second one only once. How can I solve this?

Thanks

Upvotes: 0

Views: 454

Answers (1)

DevLounge
DevLounge

Reputation: 8437

Try this:

<script>
     var app = angular.module("vp", []);
        app.controller("main", function($scope){
            $scope.name="init name";

            $scope.clickfunc = function(){
                $scope.name = Math.random();
                console.log($scope.name);
            });
        })

        app.directive("dirtest", function($compile){
            return {
                restrict: "E",
                scope: false,
                controller : function($scope){
                },
                compile: function(tEl, tAttrs){
                    return {
                        post: function(scope, el, attrs, ctrl){
                            el.append($compile("<button class='dirbtn' ng-click='clickfunc()'>{{name}}</button>")(scope)); 
                        }
                    };
                }
            }
        });
</script>

Upvotes: 1

Related Questions