我编写了一个指令,大致是这个样子:
'use strict';
myApp.directive('mySwitchOnOff', [
'$rootScope', function($rootScope) {
return {
restrict: 'C',
replace: false,
scope: { isActive: '='},
templateUrl: 'urlToTample',
link: function(scope, element, attrs) {
scope.toggleVisibility = function(section, module) {
//Do something with the scope.isActive
};
}
};
}
]);
这个指令使用了来自父级作用域的 isActive
。当用户点击按钮时,toggleVisibility
函数会被执行。我认为没有必要将来自父级作用域的 isActive
进行绑定,通过传递 $event
给函数并检查目标是否有活动类,我可以找到按钮是否是 isActive
。所以我把指令改写成了这样:
'use strict';
myApp.directive('mySwitchOnOff', [
'$rootScope', function($rootScope) {
return {
restrict: 'C',
replace: false,
templateUrl: 'urlToTample',
link: function(scope, element, attrs) {
scope.toggleVisibility = function(e, section, module) {
isActive = j$(e.target).hasClass('active');
//Do something with the isActive
};
}
};
}
]);
我的问题是:从性能/最佳实践的角度来看,你认为哪种方式更好?是将父作用域绑定还是将$event传递到函数中?