AngularJS – 创建一个添加兄弟元素的指令

前端之家收集整理的这篇文章主要介绍了AngularJS – 创建一个添加兄弟元素的指令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在创建一个my-validate指令,看起来像这样

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

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

错误模板:

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

错误在指令范围内定义.

我在编译函数添加错误模板,但我遇到的问题是链接函数中的作用域与附加的模板不同.

这是一个说明问题的plunker:http://plnkr.co/edit/ghdtdYruQaaO0Yxxlrt1?p=preview

在指令模板中可以看到’world’,但在添加的元素上看不到:S.

解决方法

那是因为你的div“2 hello”在你的范围可见的容器之外.
您可以使用element.append()而不是element.after()来使范围可用.

指示

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相关文章