【问题标题】:Modify the template of a directive to access the same scope as the directive that created it修改指令的模板以访问与创建它的指令相同的范围
【发布时间】:2014-03-14 18:56:17
【问题描述】:

AngularJs 新手在这里。首先,我可能把这一切都搞错了,所以请随时就我的方法提供任何建议。我正在尝试做的是拥有一个应用模板的元素指令。这是初始指令 myDirective

directives.directive('myDirective', [function() {

    var template = "<button type='button' class='btn btn-default' my-other-directive={{model}}>CLICK ME</button>";

    function link(scope, element, attrs) {

    };

    return {
        restrict: 'E',
        link: link,
        scope: {
            model: '@'
        },
        template: template
    };
}]);

它在我的 HTML 中被这样引用。

<my-Directive model="ThisVaries"></my-Directive>

这里是 'myOtherDirective'

directives.directive('myOtherDirective', [function() {

    function link(scope, element, attrs) {

       var attr = attrs.myOtherDirective;

       element.bind('click', function() {
           scope.$parent.$parent.data.contact[attr].splice(0, 1); // need the index of the item
       });
    };

    return {
        restrict: 'A',
        link: link
    };
}]);

基本上,这是一个联系表单,用户将在其中单击按钮,然后从控制器 scope.data.contact[variable][index] 中删除该项目。我能够获取传入的 attr 变量以访问祖父母的 scope.data 变量,但是当我单击按钮时模型不会更新。

我昨天刚开始使用指令,我很确定这不是正确的方法。任何帮助都会有所帮助。

我的 controller.js 文件中的控制器包含 $scope.data 属性,它是整个 html 部分的控制器。

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    Angular 通过在 $digest 循环中执行所有内容来实现其神奇的双向绑定,但是当事件发生在 Angular 已经执行的某些内容之外时(例如由您的 element.bind('click' 触发的 click 事件),您将需要通过使用scope.$apply 运行它来手动指示它返回 $digest 循环。

    应用于您的示例:

    directives.directive('myOtherDirective', [function() {
    
        function link(scope, element, attrs) {
    
            var attr = attrs.myOtherDirective;
    
            element.bind('click', function() {
                scope.$apply(function() {
                  scope.$parent.$parent.data.contact[attr].splice({0, 1}); // need the index of the item
                })
            });
        };
    
        return {
            restrict: 'A',
            link: link
        };
    }]);
    

    【讨论】:

    • 效果很好。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 2014-12-01
    • 2014-09-06
    • 1970-01-01
    相关资源
    最近更新 更多