AngularJS中点击事件触发时回调函数未执行问题求助
Hey there, let's break down why your callback functions aren't triggering when you click those tab buttons, and how to fix it!
The Core Issue
When you reference tab.callbackFunc in your on-click attribute, two key problems are happening:
- Lost
thisContext: The callback functions (firstPrint/secondPrint) are defined on your controller instance, but when you store them in thetabListarray, they lose their binding to the controller'sthisvalue. - Expression Expectation: If your
tool-bar-buttondirective uses AngularJS's&binding for theon-clickattribute (standard for callback inputs), it expects an executable expression—not just a raw function reference.
Solution 1: Bind the Function Context
First, ensure each callback in tabList retains its connection to the controller. You have two straightforward ways to do this:
Option A: Use bind()
Update your controller's tabList initialization to bind each function to this:
this.tabList = [ {callbackFunc: this.firstPrint.bind(this), isBtnSelected: this.isASelected}, {callbackFunc: this.secondPrint.bind(this), isBtnSelected: this.isBSelected} ];
Option B: Use Arrow Functions (ES6+)
Wrap each callback in an arrow function, which preserves the surrounding this context automatically:
this.tabList = [ {callbackFunc: () => this.firstPrint(), isBtnSelected: this.isASelected}, {callbackFunc: () => this.secondPrint(), isBtnSelected: this.isBSelected} ];
Solution 2: Update the on-click Expression
Next, modify your HTML to call the function explicitly in the on-click attribute. Since the directive expects an executable expression, add parentheses to trigger the function:
<div class="tabs-container"> <button ng-repeat="tab in $ctrl.tabList" ng-click="$ctrl.selectTab($index)"> <tool-bar-button on-click="tab.callbackFunc()" is-button-selected="tab.isBtnSelected"> </tool-bar-button> </button> </div>
Why Directly Using $ctrl.firstPrint Works
When you write on-click="$ctrl.firstPrint", AngularJS automatically resolves the function within the controller's scope and maintains the correct this context. The tabList approach breaks this because the function is detached from its original scope before being passed to the directive.
Quick Test
After making these changes, click your tab buttons again—your callbacks should now fire as expected! If you're still having issues, double-check that your tool-bar-button directive is correctly set up to handle the on-click binding with & in its definition.
内容的提问来源于stack exchange,提问作者B. Nir

