sQer
sQer

Reputation: 1151

Use angular controller in dynamically loaded html

I have following code

app.js

var app = angular.module('myModule', ['schemaForm', 'base64', 'ngRoute']);

taskController.js

app.controller('TaskController', function($scope, AuthService, $http, $base64, $location) {
    $scope.fetchFormKey = function() {
        $http.defaults.headers.common['Authorization'] = 'Basic ' + AuthService.auth;
        $http.get(restServerURL + '/task/' + $scope.taskId + '/form').
        success(function(data) {
            $scope.formKey = "./partials/itpTrainingCreation/" + data.key + ".html";
        });
    }

}

task.html

<h2>Generated form</h2>
<div ng-controller="TaskController" ng-init="fetchFormKey()">
    <div ng-include src="formKey"></div>
</div>

In dynamically loaded file (loaded by ng-include) i want to define angular controller which will be used by this file.

dynamic.html (example)

<script>
angular.module('myModule').controller('DymanicController', function($scope, AuthService, $http, $base64, $location) {
 $scope.exampleValue="myCustomValue";
});
</script>
<div ng-controller="DymanicController">
    {{exampleValue}}
</div>

Unfortunately i get following error: http://errors.angularjs.org/1.5.5/ng/areq?p0=DymanicController&p1=not%20a%20function%2C%20got%20undefined

How can I change my code to fix this problem?

Upvotes: 0

Views: 216

Answers (3)

sQer
sQer

Reputation: 1151

I found similar question how to include javascript file specific to each view angularjs

    You can't. Angular does not load javascript parts from a template.
    What you should do is to include them in your main application anyway.
    All of the controllers should be loaded while the main app is initiating. 

Could someone confirm this thesis?

Upvotes: 0

Shubham Takode
Shubham Takode

Reputation: 533

I assume your dynamic contents have some template. I think you should take look at script in angularjs

<script type="text/ng-template" id="/tpl.html">
  Content of the template.
</script>

and use ui-routing to add your dynamic content, assign controller there in router.

Upvotes: 2

Daniel
Daniel

Reputation: 609

If you wanna load a module on the fly I recommend ocLazyload. That worked pretty well in one side project of mine.

myApp.controller("MyCtrl", function($ocLazyLoad) {
  $ocLazyLoad.load('testModule.js');
});

works well with routers.

Upvotes: 0

Related Questions