2017-03-27 61 views
-2

我有app.js文件和watchExample.js文件,它有一個控制器。我在app.js中將這個控制器注入到我的應用程序中。所以我不想在我的index.html頭文件中加載watchExample.js文件。因爲如果我有很多js文件,我將不得不將它們加載到我的頭標記中。所以這對我來說似乎很骯髒。爲什麼我必須加載我的每個額外的js文件,我已經在app.js注入它們了?或者有沒有更好的方法來做到這一點?AngularJS包含部分js文件,不用在HTML頭中加載

的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; 
     }); 
    }]); 
+0

好一個角不注入代碼,你覺得它的方式。但是,有些工具可以使用,因此您不必在HTML中手動添加每個腳本標記,例如[Gulp](http://gulpjs.com/) – George

回答

0

見瘸語言只是爲了讓你明白。

假設有一家雜貨店,當你去那裏時,你會發現什麼?幾乎所有的雜貨都是對的? 現在你想要一些蔬菜,所以你會把它們全部?當然不,你會得到你想要的。

當你給src =「」那麼整個js文件「REMEBER JS文件及其源代碼」加載到你的HTML應用程序,現在你想從它裏面的東西。例如一些函數(),你會調用function_name()或src =「」..

所以src只是加載頁面中的所有數據,注入只是用來從文件中獲取函數。


爲你另一個問題「更好的辦法」是使用gulp。

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

什麼一飲而盡做的是combile所有的JS文件到一個(它的特點之一)