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

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

问题描述

我创建一个我-验证指令,它看起来像这样

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> 

错误在指令的范围界定。

我已经添加了编译函数的错误模板,但我有问题是,范围在链接函数是不一样的附加模板

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/编辑/ ghdtdYruQaaO0Yxxlrt1?p = preVIEW

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

世界被认为是在该指令模板,但不添加元素上:S。

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

推荐答案

这是因为你的DIV2你好是你的范围是可见的容器外。
您可以使用 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=$p$ PVIEW

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

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