我写了一个类似这样的指令:
'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
,我可以通过将isActive
传递给函数来查找按钮$event
并检查目标是否具有活动类。所以我重写了这样的指令:
'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
};
}
};
}
]);
我的问题是:从性能/最佳实践的角度来看,您认为最好的是什么?绑定父范围或将$事件传递给函数?
答案 0 :(得分:0)
有趣的问题,
我认为既然您已经使用ng-click调用了摘要周期,而不是查询dom(即使hasClass是性能相当低的调用) - 即绑定父作用域会更快。
你的hasClass的含义: (来自jquery来源)
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 &&
(" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
手表周期也不便宜,但无论如何它都会发生,所以它会检查参考并根据需要触发手表动作,但由于它已经发生,我认为它更快。
但我只是猜测:)