[英]why can't angular js can't find the custom controller
我在单独的文件中创建了一个自定义的angularjs控制器,并且调用方也在单独的文件中。 但是由于某种原因,angularjs给出的错误控制器未定义。 这些是文件:
test_ctrl.js:
function test_ctrl($scope, $rootScope, apiSrvc, $mdDialog) {
$scope.hide = function() {$mdDialog.hide();};
$scope.cancel = function() {$mdDialog.cancel();};
}
index.html:
<button id="testbutton" ng-click="openModal($event)">open modal</button>
index.js:
// Open the Modal //
$scope.openModal = function(ev) {
$mdDialog.show({
controller: test_ctrl,
templateUrl: '/views/testview/testmodal.html',
parent: angular.element($('.some_parent_class')),
targetEvent: ev,
clickOutsideToClose:true,
locals: {},
onRemoving: function (event, removePromise) {
}
});
};
//*/
});
testmodal.html:
<md-dialog>
<md-dialog-content>
testing content
</md-dialog-content>
<md-dialog-actions layout="row">
<md-button ng-click="cancel()">Close</md-button>
</md-dialog-actions>
</md-dialog>
好的,总结一下过程,index.html中的按钮应该打开一个角度模态对话框。 所以对于按钮的index.html我列入“NG-点击=” openModal($事件)”触发角事件,打开角度模式的。我不知道我丢失或做错了,但在控制台单击按钮时,出现““ test_ctrl”未在angular中定义...“错误。我在做什么错?
编辑好了另一种方式来绕过它是包含在同一文件index.js控制器定义功能,但我真的希望包括在openModal参数外部控制器文件的位置一样,你可以用模态模板位置(templateUrl: '/views/testview/testmodal.html')。 控制器文件的位置是否有参数?
控制器功能定义需要在index.js
加载之前定义,因此在index.html中,您需要在index.js
之前加载test_ctrl.js
。
较干净的替代方法是将控制器功能导入index.js
。
我将控制器放在外部文件中,并使用openModal angular方法对其进行调用。 有没有一种方法可以在openModal参数中定义控制器文件的位置?
将控制器定义为模块的一部分:
angular.module("test",[])
.controller("test_ctrl",
function test_ctrl($scope, $rootScope, apiSrvc, $mdDialog) {
$scope.hide = function() {$mdDialog.hide();};
$scope.cancel = function() {$mdDialog.cancel();};
})
在主模块中,将其声明为依赖项:
angular.module("app",['test'])
在模式中,使用字符串调用:
$scope.openModal = function(ev) {
$mdDialog.show({
controller: ̶t̶e̶s̶t̶_̶c̶t̶r̶l̶,̶ "test_ctrl",
templateUrl: '/views/testview/testmodal.html',
parent: angular.element($('.some_parent_class')),
targetEvent: ev,
clickOutsideToClose:true,
locals: {},
onRemoving: function (event, removePromise) {
}
});
};
有关更多信息,请参见AngularJS开发人员指南-模块
当将其定义为模块的一部分时,我可以将该代码放入外部文件中,对吗? 而不明确告诉angular它在哪里或是否将其包含在script标签中?
包含模块的文件可以按任何顺序加载(在angular.js
之后)。 当框架找到ng-app
指令并构建应用程序时,将对依赖项进行整理。
有关更多信息,请参见John Papa AngularJS样式指南-模块
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.