Javascript 在链接中实现函数或将$scope传递给链接外的函数
我的问题是什么是最佳实践+更有效? 在Link函数内部实现使用$scope的函数,还是在外部实现并将$scope传递给它Javascript 在链接中实现函数或将$scope传递给链接外的函数,javascript,angularjs,angularjs-directive,angularjs-scope,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,我的问题是什么是最佳实践+更有效? 在Link函数内部实现使用$scope的函数,还是在外部实现并将$scope传递给它 angular.module('exampleModule', []) .directive('exampleDirective', ['$http', function ($http) { return { restrict: 'EA', scope: {
angular.module('exampleModule', [])
.directive('exampleDirective', ['$http',
function ($http) {
return {
restrict: 'EA',
scope: {
...
},
link: function ($scope, element, attr) {
/* Implement here? */
function myFunc(){
/* do some calc using $scope*/
}
},
templateUrl: "..."
}
/**
* Assistant Functions
*/
/* Implement here? */
function myFunc($scope){
/* do some calc using $scope*/
}
}]);
您可以在底部定义函数,只需提供对该函数的引用,该函数将在需要时接收所有参数 例如
你不必总是传递匿名函数,你可以传递任何函数引用,当调用该函数时,它将被赋予三个参数,这样你就可以直接在函数中获得该参数,而无需创建额外的作用域和函数层。Imo在外部实现它只会使代码更混乱,更复杂更难阅读-只需将其放在链接函数中,这样任何阅读它的人都会理解发生了什么。这个问题根本没有意义。这就像“三明治需要哪种蛋黄酱?”。嗨,山姆,问题不在于链接函数本身,而在于在链接函数内部或外部声明其他函数。你可以在链接函数外部或内部声明任何函数,我认为将其保留在外部是好的,不要将$scope传递给任何其他函数,您的函数应该是纯函数,它只接受参数和返回结果,在主函数中使用这些参数并在必要时添加到作用域中,这样您就不必将作用域传递给任何其他函数。例如,我正在更新答案。
angular.module('exampleModule', [])
.directive('exampleDirective', ['$http',
function ($http) {
return {
restrict: 'EA',
scope: {
...
},
link: myFunc, // just the reference to the function to be invoked
templateUrl: "..."
}
//link function
function myFunc($scope, element, attr){
/* do some calc using $scope*/
$scope.someResult = calculateSomeResult($scope.someArg);
// use the sub function to perform calculation and give only required thing as argument, don't pass entire $scope
}
function calculateSomeResult(someArg) {
return someArg * 2; //here perform any calculation or anything. and return the result
}
}]);