我正在尝试在单独的文件中定义控制器,但我收到了错误:
transactionsController not a function got undefined
文件结构
我按此顺序添加了文件 1- common.js 2- transactions.js
Common.js 在我定义的常见文件中
var app = angular.module("spModule", ["ngMessages", "ui.bootstrap"]);
Transactions.js
angular.module('spModule').controller('transactionsController',
['$scope', '$http', function ($scope, $http) {} ]
);
HTML文件
<body ng-app="spModule" ng-controller="transactionsController">
答案 0 :(得分:59)
首先,你应该摆脱全局app
变量。这不是必需的。其次,您必须了解angular.module()
方法的原理。
将angular.module()
与两个参数(例如angular.module('my-module', [])
)一起使用会导致设置一个具有相应依赖关系的新模块。相反,使用angular.module('my-module')
时,会在内部查找相应的模块并返回给调用者(获取)。
首次定义应用程序时的方法可能只是创建以下文件和结构。
<强> app.js 强>
angular.module('myApp', []);
<强> FirstController.js 强>
angular.module('myApp').controller('FirstController', function () {});
<强> SecondController.js 强>
angular.module('myApp').controller('SecondController', function () {});
如果你现在按照这个特别的顺序在html文档中包含这些文件(至少 app.js 必须先来),你的应用程序可以在两个独立的文件中使用两个独立的控制器。
我可以推荐AngularJS Styleguide on modules以获得有关此主题的更多想法。
答案 1 :(得分:3)
你可以把这个控制器放在像mycontroller1.js这样的单独文件中
app.controller('myController', ['$scope',function($scope)
{
$scope.myValue='hello World'
}])
同样这样你可以创建新的js文件'myNewcontroller.js'并且可以放置新的控制器:
app.controller('myController2', ['$scope',function($scope) { $scope.myValue='hello World' }])
希望这会对你有所帮助:)干杯!!
答案 2 :(得分:3)
您可以通过创建模块来完成这些工作。创建模块和相应的控制器。并将该模块注入主app模块。
>>> from itertools import product
>>> all_outcomes = product(("heads", "tails"), repeat=3)
>>> list(all_outcomes)
[('heads', 'heads', 'heads'), ('heads', 'heads', 'tails'), ...]
现在注入&#34; tmodule&#34;到您的Common.js文件 -
Transactions.js
(function() {
'use strict';
angular.module('tmodule', []);
})();
(function() {
'use strict';
angular.module('tmodule').controller('transactionsController', ['$scope', '$http',
function ($scope, $http){
}]);
})();
答案 3 :(得分:1)
首先加载你的common.js.将ng-app指令移至<html>
标记。将transaction.js更改为:
app.controller('transactionsController', TransactionsController)
TransactionsController.$inject = ['$scope','$http']
function TransactionsController($scope, $http) {
};
只是为了好玩。让我知道会发生什么。