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

4
  • 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. Commented Nov 5, 2014 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. Commented Nov 5, 2014 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 Commented Nov 5, 2014 at 14:57
  • you should really read thinking-in-angularjs-if-i-have-a-jquery-background Commented Nov 5, 2014 at 14:59

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

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.