指令可以从父作用域中删除自身吗 [英] Can a directive delete itself from a parent scope

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

问题描述

假设我有以下代码

<div ng-repeat="实例中的实例><customDirective ng-model="instance"></customDirective>

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

 app.directive('customDirective', function($log) {返回 {限制:'E',templateUrl: './template.htm',范围:{_instance:"=ngModel"},链接:函数($scope){....}});

在这个指令中,我必须选择删除它.我的问题是如何与父作用域中的数组实例通信并告诉它销毁此对象并实际上从我的 DOM 中删除已删除的实例?

希望这是有道理的.

解决方案

根据 之前的评论,是这样的:

var app = angular.module('app', []).directive('customDirective', function($log) {返回 {限制:'EA',模板:'<a href="" ng-click="onRemove()">删除我{{model.n}}</a>',范围: {型号:"=",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 在实例中"><custom-directive model="i" on-remove="instances.splice($index,1)"></custom-directive>

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天全站免登陆