我有一个用于AngularJS网页的自调用函数。如您所见,我有一个名为getData()的函数,其工作是在页面加载时以及随后根据用户与页面的交互进行ajax调用以获取一些数据。
<script type="text/javascript">
// Should I defne it here like this completely outside the self invoking
// function with or without var keyword
getData = function (reqData) {
alert(reqData); // Ajax call here...
};
(function () {
// Should I defne it here like this?
getData = function (reqData) {
alert(reqData); // Ajax call here...
};
//Should I have to use the var key word like so
var getData = function (reqData) {
alert(reqData);// Ajax call here...
};
PatientCategoryController = function ($http, $scope, uiGridConstants) {
// Should I defne it here like this inside the controller?
getData = function (reqData) {
alert(reqData);// Ajax call here...
};
//Should I have to use the var key word inside the controller?
var getData = function (reqData) {
alert(reqData);// Ajax call here...
};
// Or should I define the function on the $scope object like so?
$scope.getData = function (reqData) {
alert(reqData);// Ajax call here...
};
angular.element(document).ready(getData('someDataToPass'));
}
PatientCategoryController.$inject = ['$http', '$scope', 'uiGridConstants'];
angular.module('demoApp', ['ui.grid', 'ui.grid.autoResize', 'ui.grid.pagination']);
angular.module('demoApp').controller('PatientCategoryController', PatientCategoryController);
}());
</script>
我的问题是应该如何定义这个函数? 应该在$scope对象上定义吗? 还是应该与控制器并列定义? 或者应该将其完全定义在自调用函数之外?
还有类似的情况, 我应该在哪里定义javascript对象,以保存可能需要进行ajax调用的数据.
我开始构建这个页面,但某个时刻,javascript开始表现异常,所以我不得不从头开始。这就是我问这个问题的原因.
过去我阅读并尝试了解javascript,但除了浏览器端以外,我从未进行过任何严肃的javascript编程。这个应用程序本身是在Asp.Net mvc中的。所以我对javascript永远不感到自信,并且经常陷入这种麻烦中。请指导我。