亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何創建單獨的AngularJS控制器文件?

如何創建單獨的AngularJS控制器文件?

PIPIONE 2019-08-06 13:18:34
如何創建單獨的AngularJS控制器文件?我將所有AngularJS控制器都放在一個文件controllers.js中。該文件的結構如下:angular.module('myApp.controllers', [])   .controller('Ctrl1', ['$scope', '$http', function($scope, $http) {       }])   .controller('Ctrl2', ['$scope', '$http', function($scope, $http) }   }])我想做的是將Ctrl1和Ctrl2放入單獨的文件中。然后我會在index.html中包含這兩個文件,但是應該如何構建呢?我嘗試做這樣的事情,它在Web瀏覽器控制臺中拋出一個錯誤,說它無法找到我的控制器。任何提示?
查看完整描述

3 回答

?
侃侃無極

TA貢獻2051條經驗 獲得超10個贊

文件一:

angular.module('myApp.controllers', []);

文件二:

angular.module('myApp.controllers').controller('Ctrl1', ['$scope', '$http', function($scope, $http){}]);

檔案三:

angular.module('myApp.controllers').controller('Ctrl2', ['$scope', '$http', function($scope, $http){}]);

包括在那個順序中。我推薦3個文件,因此模塊聲明是獨立的。


關于文件夾結構,關于這個主題有很多很多意見,但這兩個都很不錯

https://github.com/angular/angular-seed

http://briantford.com/blog/huuuuuge-angular-apps.html


查看完整回答
反對 回復 2019-08-06
?
DIEA

TA貢獻1820條經驗 獲得超2個贊

在末尾使用帶有數組的angular.module API 將告訴angular創建一個新模塊:

myApp.js

// It is like saying "create a new module"angular.module('myApp.controllers', []); // Notice the empty array at the end here

在沒有數組的情況下使用它實際上是一個getter函數。因此,要分離您的控制器,您可以:

Ctrl1.js

// It is just like saying "get this module and create a controller"angular.module('myApp.controllers').controller('Ctrlr1', ['$scope', '$http', function($scope, $http) {}]);

Ctrl2.js

angular.module('myApp.controllers').controller('Ctrlr2', ['$scope', '$http', function($scope, $http) {}]);

在你的javascript導入過程中,只需確保myApp.js在AngularJS之后,但在任何控制器/服務/等之前...否則angular將無法初始化你的控制器。


查看完整回答
反對 回復 2019-08-06
?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

雖然這兩個答案在技術上都是正確的,但我想為此答案引入不同的語法選擇。這個imho可以更容易地閱讀注射的內容,區分等。


文件一


// Create the module that deals with controllers

angular.module('myApp.controllers', []);

文件二


// Here we get the module we created in file one

angular.module('myApp.controllers')


// We are adding a function called Ctrl1

// to the module we got in the line above

.controller('Ctrl1', Ctrl1);


// Inject my dependencies

Ctrl1.$inject = ['$scope', '$http'];


// Now create our controller function with all necessary logic

function Ctrl1($scope, $http) {

  // Logic here

}

文件三


// Here we get the module we created in file one

angular.module('myApp.controllers')


// We are adding a function called Ctrl2

// to the module we got in the line above

.controller('Ctrl2', Ctrl2);


// Inject my dependencies

Ctrl2.$inject = ['$scope', '$http'];


// Now create our controller function with all necessary logic

function Ctrl2($scope, $http) {

  // Logic here

}


查看完整回答
反對 回復 2019-08-06
  • 3 回答
  • 0 關注
  • 804 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號