AngularJS - 创建一个添加同级元素的指令 [英] AngularJS - Create a directive that adds a sibling element

查看:20
本文介绍了AngularJS - 创建一个添加同级元素的指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个看起来像这样的 my-validate 指令

I'm creating a my-validate directive that looks something like this

<input my-validate="customValidation" ng-model="model" />

我想要做的是将一个sybling元素附加到这样的指令

What I want to do is to attach a sybling element to the directive like this

错误模板:

<ul class"errors">
   <li ng-repeat="for error in errors">{{error}} not valid</li>
</ul> 

errors 在指令范围内定义.

我已经在compile函数中添加了错误模板,但是我遇到的问题是link函数中的scope和附加的模板不一样.

I've added the error template in the compile function, but the problem I have is that the scope in the link function is not the same as the attached template.

这里有一个 plunker 来说明这个问题:http://plnkr.co/edit/ghdtdYruQaaO0Yxxlrt1?p=预览

Here is a plunker to illustrate the issue: http://plnkr.co/edit/ghdtdYruQaaO0Yxxlrt1?p=preview

'world' 出现在指令模板中,但不在添加的元素 :S 中.

'world' is seen in the directive template, but not on the added element :S.

推荐答案

那是因为您的 div "2 hello" 位于您的作用域可见的容器之外.您可以使用 element.append() 而不是 element.after() 来使范围可用.

That's because your div "2 hello" is outside the container where your scope is visible. you can use element.append() instead of element.after() to have the scope available.

var app = angular.module('plunker', []);


app.directive('myValidate', function($compile) {
      return {
        template: '<span>1. Hello {{world}}  my scope is {{$id}} (parent: {{$parent.$id}})<span/>',
        replace: true,
        restrict: 'A',
        scope: true,
        compile: function (element) {

          element.append('<div>2. Hello {{ world }}, my scope is {{$id}} (parent: {{$parent.$id}})</div>');

          return function(scope) {
            scope.world = 'World';
            //$compile()(scope);
          };
        }
      };
});

HTML

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script data-require="angular.js@1.1.5" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="app.js"></script>
  </head>

  <body>
    <input my-validate="" />
  </body>

</html>

http://plnkr.co/edit/dU3holBCePKe0ZAwQKh1?p=preview

这篇关于AngularJS - 创建一个添加同级元素的指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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