Angularjs分解控制器
我有一些很长的angularjs控制器。有哪些方法可以将它们划分为更具组织性的部分。其目的是使它们更易于维护。您可以尝试以下方法:Angularjs分解控制器,angularjs,Angularjs,我有一些很长的angularjs控制器。有哪些方法可以将它们划分为更具组织性的部分。其目的是使它们更易于维护。您可以尝试以下方法: Function.prototype.externalCall = function (varsInContext) { var fToBind = this, fNOP = function () {}, fBound = function () { for(v in varsIn
Function.prototype.externalCall = function (varsInContext) {
var
fToBind = this,
fNOP = function () {},
fBound = function () {
for(v in varsInContext) {
this[v] = varsInContext[v];
}
return fToBind.apply(this, Array.prototype.slice.call(arguments));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}
var externalFunction = function (scope) {
console.log('hello "' + scope.name + '" ' + '"' + this.scope2.lastName + '"');
scope.name = 'Hooo ' + scope.name
this.scope2.lastName = 'Huuu ' + this.scope2.lastName
};
var c = function (scope2) {
this.f = externalFunction.externalCall(
{
scope2: scope2
}
);
};
var scope2 = {};
scope2.lastName = 'Descalzo';
var o = new c(scope2);
var scope = {};
scope.name = 'Andres';
o.f(scope);
console.log(scope);
console.log(scope2);
例如,如果您的控制器与此类似:
var myApp = angular.module('myApp',[]);
myApp.controller('ContactController', ['$scope', function($scope) {
$scope.contacts = ["hi@email.com", "hello@email.com"];
$scope.add = function() {
$scope.contacts.push($scope.contact);
$scope.contact = "";
};
}]);
您可以对此进行更改:
(function() {
var myApp = angular.module('myApp',[]);
myApp.controller('ContactController', ['$scope', function($scope) {
$scope.contacts = ["hi@email.com", "hello@email.com"];
$scope.add = addContact.externalCall({ $scope: $scope });
}]);
function addContact() {
this.$scope.contacts.push(this.$scope.contact);
this.$scope.contact = "";
}
}());
注意:扩展代码基于我建议您将代码组织到可重用的模块中。例如,假设您刚刚创建了一个自定义模态对话框插件:ngModal.js。您可以将此模块的所有代码组织在一个或多个文件中:
angular.module('ngModal', ['ngAnimate'])
.directive('ngDir1', function() {
...
})
.directive('ngDir2', function() {
...
})
.controller('ngCtrl1', function() {
...
})
.config(function() {
...
});
模块做一件事(创建模态对话框),在本例中,有一个模块依赖项:ngAnimate
每当您需要在另一个应用程序中使用此插件时,您所需要做的就是引用依赖脚本文件,并添加“ngModal”作为依赖项
例如:
var myNewApp=angular.module(“myNewApp”,“ngModal”)