修改指令的模板,使其访问与创建它的指令相同的作用域

Modify the template of a directive to access the same scope as the directive that created it

本文关键字:指令 创建 作用域 修改 访问      更新时间:2023-09-26

这里是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变量来访问祖父母的作用域。数据变量,但当我点击按钮时,模型不更新。

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

controller.js文件中的控制器包含$作用域。Data属性,它是整个HTML部分的控制器。

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
    };
}]);