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?