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?

6
  • Where is your angular.module? In the template script, the app of app.controller might be undefined. Whats the error msg in the console? Commented Sep 28, 2015 at 4:36
  • @cheekybastard Hi I updated the error log in the question. Please have a look. Commented Sep 28, 2015 at 7: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 Commented Sep 28, 2015 at 9: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. Commented Sep 28, 2015 at 9:34
  • You need to make a plunkr/codepen/etc demo for anyone to help debug. Your question doesn't contain all the code. Commented Sep 28, 2015 at 11:45

0

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.