javascript - 使用 AngularJS 指令修改 Controller 数据

标签 javascript angularjs angularjs-directive

指令代码

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/

相关文章:

javascript - 简单的jquery延迟队列

Angularjs:使用 $resource 传递 token ?

javascript - 在 angularjs 指令中不起作用的标签

javascript - HTML 中的 Angular 访问指令 Controller 变量

angularjs - 一个元素的多个指令可以共享一个隔离的范围吗?

javascript - HtmlWebpackPlugin 不包含 vendor.js

javascript - jQuery $.post 不工作?

javascript - jQuery 碰撞。获取碰撞元素?

javascript - AngularJS 的数据流问题

javascript - 如何在angularJS中将自动完成下拉列表作为网格?