Javascript 指令模板中的角度调用控制器方法
我使用angular创建简单项目,并使用指令创建一个简单网格,如以下代码所示: 我的指示:Javascript 指令模板中的角度调用控制器方法,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我使用angular创建简单项目,并使用指令创建一个简单网格,如以下代码所示: 我的指示: app.directive('dpGrid',()=>{ return{ restrict:"E", scope:{ items:"=" } templateUrl: 'template/dbgrid.directive.html' } }); 我的控制器: app.controller
app.directive('dpGrid',()=>{
return{
restrict:"E",
scope:{
items:"="
}
templateUrl: 'template/dbgrid.directive.html'
}
});
我的控制器:
app.controller('mainCtrl',($scope)=>{
$scope.data=[{fname:"david",lname:"orman",age:24,id:"234"}];
$scope.update=(id)=>{
console.log("ID :",id);
};
});
我的指令模板:
<table class="table">
<thead class="thead-inverse">
<tr>
<th>#</th>
<th>fname</th>
<th>lname</th>
<th>age</th>
<th>opt</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items" >
<th>{{$index}}</th>
<td>{{item.fname}}</td>
<td>{{item.lname}}</td>
<td>{{item.age}}</td>
<td><a class="btn btn-danger" ng-click="update(item.id)">update</a></td>
</tr>
</tbody>
</table>
我使用这样的指令:
<dp-grid items="data" ></dp-grid>
我想从指令模板调用更新方法,但单击更新btn时不要调用更新方法。您只需指定指令应使用的控制器,然后在模板中访问它
return {
restrict:"E",
scope:{
items:"="
},
controller: 'mainCtrl',
templateUrl: 'template/dbgrid.directive.html'
}
然后,您将能够访问模板中的函数。如果您是从子隔离作用域访问它,您可能需要使用$parent来访问它。问题是什么?如果它在模板中,它将有权访问作用域方法。试试看会发生什么。