有没有办法在angularjs中使用partials进行代码分组?
原因---我有一个包含太多代码的控制器。该控制器包含代码对于几种方法和许多功能,它降低了代码的可读性。我想保持控制器名称相同并进行代码分组。
前: -
SELECT a.id,
a.creator,
a.date,
a.title AS product_title,
a.introimg,
a.price,
a.currency,
a.city,
a.shetanxmebit,
a.publish_date
FROM mar_home_main a
INNER JOIN
(
SELECT creator, MAX(date) AS latest_date
FROM mar_home_main
WHERE introimg!=""
AND publish=1 AND
visible=1
GROUP BY creator
) sub0
ON a.creator = sub0.creator
ON a.date = sub0.latest_date
WHERE introimg!=""
AND publish=1
AND visible=1
ORDER BY publish_date DESC
LIMIT 20
部分:
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;
});
我需要像这样实现它。
还有其他方法吗?是的请更新.. 感谢
答案 0 :(得分:1)
您可以尝试将代码排序为逻辑块。之后,您可以将逻辑块合并到对象中。
//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 } }
此外,您可以将一些代码移动到服务或工厂中。然后在控制器内部使用这些方法。
//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();
});
如果您需要服务内部的控制器功能,您仍然可以访问范围和其他类似的控制器属性。
注意:确保创建一个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'