指令代码
app.directive('uiSwitch', function() {
return {
restrict: 'E',
replace: true,
templateUrl: '_lib/custom/ui-switch/ui-switch-template.html', // markup for template
scope: {
info: '='
},
link: function(scope, el, attrs){
el.click(function(){
// How do I change the controller data here?
});
}
};
});
指令模板代码:
<button class="switch-container" ng-click="info.callback()" ng-class="{off: info.off}">
<div class="switch-inner">
<div class="option option-on">{{info.labels[0]}}</div>
<div class="switch"></div>
<div class="option option-off">{{info.labels[1]}}</div>
</div>
<div class="shadow"></div>
</button>
如何从 Controller 模板调用指令:
<ui-switch info="switch"></ui-switch>
以及我的 Controller 中的相关代码:
$scope.switch = {
labels: ['Friend', 'Foe'],
callback: function(){
c('switch clicked')
}
}
我想在单击开关时更新 Controller 上的某些属性,例如。 $scope.switch.isOff = false
。但是,我不知道如何从指令的 link()
函数中更新 Controller 的数据。
最佳答案
link
函数将 scope
作为函数的第一个参数传入。如果您的数据位于同一范围
,请通过以下方式访问它:
link: function(scope, el, attrs){
el.click(function(){
scope.switch.isOff = false;
})
}
需要注意的是,el.click
不会触发 $digest
循环 - 因此,在循环发生之前,您的数据更改不会反射(reflect)在 View 中。您可以使用 $timeout
或 $apply
强制执行(请注意 $apply()
潜在问题)
关于javascript - 使用 AngularJS 指令修改 Controller 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31253589/