0

I am attempting to add a controller to a dynamically constructed div in angular. However, the controller doesn't seem to be loading and I cannot add corresponding events to the click function.

In the example below, I am constructing this div within a separate parent controller termed 'employeeTableCtrl'. Within the parent controller, when a user clicks the 'more info' button, the new divs are constructed. In the container of this child is where I am looking to attach a new controller.

$scope.moreInfo = function(employee) {
    $("<div class='employeeWindow' ng-controller='employeeWindowCtrl'> " +
                "<button class='closeButton' ng-click='close()'> x </button> </div>".appendTo("#employees");      
    }

And in the separate controller I have:

.controller('employeeWindowCtrl', [
    '$scope', function ($scope) {
        $scope.close = function() {
            alert('clicked the x');
        }
    }
])

The divs are all being constructed correctly, but the the 'employeeWindowCtrl' is not being attached such that my 'click()' function is not being executed.

Does anyone have any tips? Maybe I am approaching this all wrong?

Thanks

thebighoncho
  • 385
  • 2
  • 6
  • 20
  • Seems a strange way of doing things. ng-show would probably take care of all of this - just make the thing and show it conditionally. – Shawn Erquhart Nov 05 '14 at 14:54
  • I think you are approaching it all wrong. Let angular create the needed elements instead of manipulating DOM from your controller. Controllers are not for that. You can use `ng-if` directive for example. – akonsu Nov 05 '14 at 14:54
  • if you inject html using code outside of angular you need to use `$compile` so angular is aware of it. As others have noted this is a terrible approach – charlietfl Nov 05 '14 at 14:57
  • you should really read [thinking-in-angularjs-if-i-have-a-jquery-background](http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background) – charlietfl Nov 05 '14 at 14:59

1 Answers1

0

What you're looking for is a directive - a chunk of html that has a sort of private controller via the link function. Create the directive in a separate template, place your controller functionality (if it indeed is appropriate for a controller) in the directive's link function and use ng-show to reveal on click. If we had more code to play with I could give a better example of all of this.

https://docs.angularjs.org/guide/directive

Shawn Erquhart
  • 1,820
  • 2
  • 17
  • 30