gpt4 book ai didi

javascript - AngularJS中的 Controller 有可能(部分类)概念吗?

转载 作者:行者123 更新时间:2023-12-03 07:46:04 27 4
gpt4 key购买 nike

有什么方法可以使用 angularjs 中的部分进行代码分组吗?

原因 --- 我的 Controller 包含太多代码。该 Controller 包含了多个方法和大量功能的代码,降低了代码的可读性。我想保持 Controller 名称相同并进行代码分组。

例如:-

app.controller('MainController', function ($scope, router) {
$scope.Read = function() {

};
$scope.Write = function() {

};
$scope.Update = function() {

};
$scope.Delete = function() {

};
});

部分:

    app.controller('MainController', function ($scope, router) {
$scope.firstName = firstname;
$scope.middleName = middleName;
$scope.lastName = lastName;
});

另一个部分:

    app.controller('MainController', function ($scope, router) {
$scope.Print = function() {

};
$scope.PrintPreviw = function() {

};
});

我需要像这样实现它。

还有别的办法吗?是的,请更新..谢谢

最佳答案

您可以尝试将代码排序为逻辑 block 。之后,您可以将逻辑 block 合并为对象。

//Do NOT do this!
$scope.firstName = firstname;
$scope.middleName = middleName;
$scope.lastName = lastName;

//instead do this
var person = {
firstname: "name",
middleName: "mName",
lastName: "Lname"
}

//then in your view access them like this
{ { person.firstname } }

此外,您可以将一些代码移至服务或工厂中。然后在 Controller 内使用这些方法。

//take things out of your controller and put then in a service or factory.
app.service('notePad', function () {
return {

Read: function (newState) {
return state += state;
},

Write: function (state) {
return state += state;
},
Update: function (state) {
state = state;
},
Delete: function () {
state = null;
}

};
});

//then in your controller access them like this
//Note you do not need everything on $scope if you are not going to use it in the view.
app.controller('MainController', function ($scope, router, notePad) {
$scope.Read = notePad.Read();
$scope.Write = notePad.Write();
$scope.Update = notePad.Update();
$scope.Delete = notePad.Delete();
});

如果您需要服务内部 Controller 的功能,您仍然可以像这样访问范围和其他 Controller 属性。

注意:确保创建 onDestroy 方法来清理任何剩余变量。

//pass your scope to your service
app.controller('MainController', function ($scope, router, notePad) {
notePad.changeView($scope);
});

//munipulate your scope just like you would in a controller
app.service('notePad', function () {
function changeView(scope) {
scope.write = 'example';
}
});

//the result of the scope change in the service will show up in the view
{ { write } } == 'example'

关于javascript - AngularJS中的 Controller 有可能(部分类)概念吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35201059/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com