AngularJS如何从ng-view的模板中钩入head标签

AngularJS how to hook into the head tag from the template of the ng-view

本文关键字:head 标签 ng-view AngularJS      更新时间:2023-09-26

我习惯使用Laravel的Blade模板引擎,但现在我正在学习在前端使用AngularJS,我已经放弃了Blade。

我试图包括一些页面特定的脚本标签,我不想包括在我的主<ng-view></ng-view>

例如,我的主页看起来像这样:
<html>
    <head>
        // want to be able to inject stuff here from the ng-view's template
    </head>
    <body>
        <ng-view></ng-view>
    <body>
</html>

并且通常使用laravel,我可以在head标签中包含@yield,以便稍后在我的模板中我可以执行@section来访问head标签。我可以用Angular做一些类似的事情吗?

试试

<html ng-app="myApp">
    <head>
        <script ng-repeat="script in headScripts" ng-src="script"/>
    </head>
    <body>
        <ng-view>
            <div ng-click="addHeadScript('/scripts/new.js');"></div>
        </ng-view>
    <body>
</html>
var app = angular.module('myApp');
app.run('$rootScope', function($rootScope){
    $rootScope.headScripts = [];
    $rootScope.addHeadScript = function(src){
        $rootScope.headScripts.push(src);
    }
});