指令可以从父范围删除自身 [英] Can a directive delete itself from a parent scope

查看:229
本文介绍了指令可以从父范围删除自身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有以下的code

 < D​​IV NG-应用=应用程序NG控制器=控制器>
 < D​​IV NG重复=实例中的实例>
  < customDirective NG模型=实例>< / customDirective>
 < / DIV>
< / DIV>

和我的自定义指令有一个孤立的范围,定义为:

  app.directive('customDirective',函数($日志){
        返回{
            限制:'E',
            templateUrl:./template.htm',
            适用范围:{_instance:= ngModel},
            链接:功能($范围){
            ....
            }
        });

在这个指示,我必须选择将其删除。我的问题是如何通信回数组实例在父范围,并告诉它破坏这个对象,实际上从我的DOM删除已删除的实例?

希望是有道理的。


解决方案

根据新开发的<一个href=\"http://stackoverflow.com/questions/27934426/can-a-directive-delete-itself-from-a-parent-scope/27935378#comment44266843_27934662\">$p$pvious评论,这是这样的:

\r
\r

VAR应用= angular.module(应用,[])\r
  .directive('customDirective',函数($日志){\r
    返回{\r
        限制:EA,\r
        模板:'&LT; A HREF =NG点击=onRemove()&GT;删除我{{model.n}}&LT; / A&GT;,\r
        范围: {\r
            模式:=,\r
            onRemove:与&amp;\r
        }\r
    }\r
  })\r
  .RUN(函数($ rootScope){\r
    $ rootScope.instances = [{n为1},{n为2},{n为3},{n为4}];\r
  });

\r

&LT;脚本SRC =htt​​ps://ajax.googleapis.com/ajax /libs/angularjs/1.2.23/angular.min.js\"></script>\r
&LT; D​​IV NG-应用=应用程序&GT;\r
  &LT; D​​IV NG重复=我的情况下,&GT;\r
    &LT;自定义指令模式=我上删除=instances.splice($指数,1)&GT;\r
    &LT; /定制指令&GT;\r
  &LT; / DIV&GT;\r
&LT; / DIV&GT;

\r

\r
\r

Let's say I have the following code

<div ng-app="app" ng-controller="controller">
 <div ng-repeat="instance in instances>
  <customDirective ng-model="instance"></customDirective>
 </div>
</div>

And my custom directive has an isolated scope, defined as:

 app.directive('customDirective', function($log) {
        return {
            restrict: 'E',
            templateUrl: './template.htm',
            scope: {_instance:"=ngModel"},
            link: function($scope) {
            ....
            }
        });

In this directive, I have to option to delete it. My question is how can I communicate back to the array instances in the parent scope and tell it to destroy this object and in effect remove the deleted instance from my DOM?

Hope that makes sense.

解决方案

according to New Dev in a previous comment, this is the way:

var app = angular.module('app', [])
  .directive('customDirective', function($log) {
    return {
        restrict: 'EA',
        template: '<a href="" ng-click="onRemove()">remove me {{model.n}}</a>',
        scope: {
            model:"=",
            onRemove:"&"
        }
    }
  })
  .run(function($rootScope) {
    $rootScope.instances = [{n:1},{n:2},{n:3},{n:4}];
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-repeat="i in instances">
    <custom-directive model="i" on-remove="instances.splice($index,1)">
    </custom-directive>
  </div>
</div>

这篇关于指令可以从父范围删除自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆