0

I want to write the controller of a view together in a view template.

However, script with a view template is not executed.

I adopted Paolo Moretti's approach in AngularJS: How to make angular load script inside ng-include? to execute the js in a view template.

app.directive('script', function (){
    return {
        restrict: 'E',
        scope: false,
        link: function (scope, elem, attr) {
            if (attr.type === 'text/javascript-lazy') {
                var code = elem.text();
                var f = new Function(code);
                f();
            }
        }
    };
});

The normal script works fine: e.g. alert('abc');

But when I declare a controller in the view template, it does not work. The view template uses the controller defined within.

<script type="text/javascript-lazy">
  alert("app="+app);
  app.controller('serviceCtrl',function($scope,$routeParams){
    $scope.services=['ser1','serv2','serv3'];
    $scope.theService=$scope.services[$routeParams.id];  
  });
</script>

<div id="servicesbox" ng-controller="serviceCtrl">
    <div id="serviceheader"><span class="h1">Services</span></div>
    <p>{{theService}}</p>
</div>

When load the above template in the view, it first alerts me "app=[object Object]" which mean "app" is NOT undefined. I then get an error in the console:

"Error: [ng:areq] http://errors.angularjs.org/1.3.14/ng/areq?p0=serviceCtrl&p1=not%20a
1.#QNAN0unction%2C%20got%20undefined

When I move the controller definition to the main js file loaded by the website, the controller works fine. And the value of theService is displayed.

So what is the problem?

Community
  • 1
  • 1
Changwang Zhang
  • 2,467
  • 7
  • 38
  • 64
  • Where is your `angular.module`? In the template script, the app of app.controller might be undefined. Whats the error msg in the console? – cheekybastard Sep 28 '15 at 04:36
  • @cheekybastard Hi I updated the error log in the question. Please have a look. – Changwang Zhang Sep 28 '15 at 07:19
  • Its bad practice, but if you want to do what your doing, you need to make app a global variable, e.g. `var app = angular.module(` then the template script might not return app as undefined. Maybe do that in main.js file – cheekybastard Sep 28 '15 at 09:12
  • @cheekybastard I have just done that in the main js. Alert(app) in my template says app is NOT undefined. In stead, the error says serviceCtrl is undefined. – Changwang Zhang Sep 28 '15 at 09:34
  • You need to make a plunkr/codepen/etc demo for anyone to help debug. Your question doesn't contain all the code. – cheekybastard Sep 28 '15 at 11:45
  • This question is relevant: http://stackoverflow.com/questions/17674945/angularjs-dynamic-loading-a-controller – Changwang Zhang Sep 28 '15 at 14:18

0 Answers0