【问题标题】:AngularJS including partial js files without loading in HTML headAngularJS 包括部分 js 文件而不在 HTML 头中加载
【发布时间】:2017-03-27 09:58:34
【问题描述】:

我有 app.js 文件和 watchExample.js 文件,其中有一个控制器。我在 app.js 中将此控制器注入到我的应用程序中。所以我不想在我的 index.html 头中加载 watchExample.js 文件。因为如果我有很多 js 文件,我将不得不将它们加载到我的 head 标签中。所以这对我来说似乎很脏。为什么我必须加载每个额外的 js 文件,我已经在 app.js 中注入了它们?或者有没有更好的方法来做到这一点?

index.html

<!DOCTYPE html>
<html ng-app="watch">
    <head>   
        <title>Angular Watch</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.min.js"></script>
        <script type="text/javascript" src="app.js"></script>
        <script type="text/javascript" src="watchExample.js"></script>
    </head>
    <body ng-controller="watchExample">
        <div ng-view=""></div>        
    </body>
</html>

app.js

var app = angular.module("watch", ['ngRoute', 'watch-page']);

app.config(function($routeProvider){
    $routeProvider
        .when('/',{
            templateUrl: 'login.html' 
        })
        .when('/watch',{
            resolve: {
                "check": function($location,$rootScope){
                    if(!$rootScope.loggedIn){
                        $location.path('/');
                    }
                }
            },
            templateUrl: 'watch.html',
            controller: 'watchExample'
        })
        .otherwise({
            redirectTo: '/' 
        });    
});

watchExample.js

var app = angular.module("watch-page", []);
app.controller('watchExample', ['$scope', function ($scope) {
        $scope.counter = -1;
        $scope.$watch('myText', function (newValue, oldValue) {
            $scope.counter++;
            if($scope.counter === 50){
                alert("Yeter artık "+$scope.counter+" kere değiştirdin!");                
            }
            $scope.oldVal = oldValue;
            $scope.newVal = newValue;
        });
    }]);

【问题讨论】:

  • 好吧,Angular 不会像你想象的那样注入代码。但是,您可以使用一些工具,因此您不必在 html 中手动添加每个脚本标记,例如 Gulp

标签: javascript angularjs ngroute


【解决方案1】:

用蹩脚的语言看只是为了让你理解。

假设有一家杂货店,当你去那里时,你会发现什么?几乎所有的杂货,对吧? 现在你想要一些蔬菜,你会全部拿走吗?当然不,你会得到你想要的。

当你给 src="" 然后整个 js 文件 "记住 JS 文件及其源代码" 加载到你的 html 应用程序中,现在你想要它里面的东西。例如一些function(),你将调用function_name() 或src=""..

所以 src 只是加载页面中的所有数据,而注入只是用于从文件中获取函数。


对你来说,另一个问题“更好的方法”是使用 gulp。

https://scotch.io/tutorials/automate-your-tasks-easily-with-gulp-js

gulp 所做的就是将所有的js文件合并为一个(它是特性之一)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 2016-04-03
    • 1970-01-01
    相关资源
    最近更新 更多