0

I'm working with a legacy MVC application, and I want to implement some Angular into one of the views.

After the initial struggle of getting Angular to $compile the new DOM, I'm left with an error that i can't seem to overcome.

The way it works (and something I cannot change) is that jQuery loads the specific view/layer markup, and when its in the DOM, I do the following:

// Compiles the DOM into the Angular application
if ($layer.hasClass('angular-view')) {
    angular.injector(['ng']).invoke(function ($rootScope, $compile) {
        $compile($layer)($rootScope);
        $rootScope.$digest();
    });
}

This allows me to see the evaluated value ({{2+2}}) on the rendered page, which is great, however, when I try to compile a controller into the markup, I get the following error:

Argument 'MyController' is not a function, got undefined

This is the markup I'm injecting into the application:

<div ng-controller="MyController">
    <span>{{2+2}} - {{name}}</span>
</div>

Here's how I'm declaring the app module:

angular.module('app', [])
    .controller('MyController', function ($scope) {
        $scope.name = "Terry Nutkins";
    });

I'm initialising the application in the "main" DOM like this:

<body ng-app>
    <!-- Content -->
</body>

(I've also tried ng-app="app")

Any thoughts?


I should also add that when I query the module in the debug console, I can see the controller sitting there, ready to go.

angular.module('app')._invokeQueue[0][2][0]
"MyController"

1 Answer 1

2

I've found the cause of the issue - and I hope someone else finds this useful.

When I inject and compile the DOM, I need to specify WHICH injector I want to use. In my case, I needed to add 'app' to the array of the angular.injector call

// Compiles the DOM into the Angular application
if ($layer.hasClass('angular-view')) {
    angular.injector(['ng', 'app']).invoke(function ($rootScope, $compile) {
        $compile($layer)($rootScope);
        $rootScope.$digest();
    });
}
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.