我喜欢尽可能将代码分解成小块。所以我在研究是否可以将控制器的$ scope属性和函数/行为与控制器的大括号(范围)分开,并将其写在远离myApp范围内的任何其他位置。 (可能在不同的* .js文件中,只是将其包含在HTML文件中)
我的代码示例如下所示:
var myApp = angular.module('myApp.controllers', []);
myApp.controller('login', ['$scope', function ($scope) {
$scope.title = data.title;
$scope.lab = data.lab;
//Following is the set of code that i will use to create the login validation logic.
//I plan to put these in a new function/behavior in this same $scope.
//BUT i want these lines of code to lie outside this controller function braces.
if ($scope.email== l.email && $scope.password== l.password) {
$scope.Loginstatus = false;
} else {
$scope.Loginstatus = true;
}
}]);
我期待的是这样的:
//Now, I know the following is going to be too crude/dirty/illogical but I am trying to explain what is in my mind.
//Please forgive :)
myApp.controller.login.$scope.validate = function($scope){
if ($scope.email== l.email && $scope.password== l.password) {
$scope.Loginstatus = false;
} else {
$scope.Loginstatus = true;
}
};
请指教。
由于
答案 0 :(得分:2)
将应用程序分解为更小的模块总是有利于可读性和维护。
<强> See this 13 steps on how to modularize an angular project 强>
要快速了解angularjs项目的编写方式,请查看angular-seed项目:https://github.com/angular/angular-seed
通常,定义范围的方法和变量应该在范围内完成。
在极少数情况下,您需要修改控制器外部的范围属性:
在这种情况下,您可以在控制器外部获取范围并使用它。
var scope = angular.element(document.getelementById('el')).scope()
scope.$apply(function(){
// do whatever with scope
scope.validate = function() {
if (scope.email== l.email && scope.password== l.password) {
scope.Loginstatus = false;
} else {
scope.Loginstatus = true;
}
};
});
答案 1 :(得分:-1)
试试这个
var myApp = angular.module('myApp.controllers', []);
myApp.controller('login', ['$scope', function ($scope) {
$scope.title = data.title;
$scope.lab = data.lab;
//Following is the set of code that i will use to create the login validation logic.
//I plan to put these in a new function/behavior in this same $scope.
//BUT i want these lines of code to lie outside this controller function braces.
$scope.login = validater({name:$scope.name, password:$scope.password});
}]);
var validater = function(credentials) {
if (credentials.email== l.email && credentials.password== l.password) {
return false;
} else {
return true;
}
}