AngularJS – 创建一个添加兄弟元素的指令
发布时间:2020-12-17 17:30:52 所属栏目:安全 来源:网络整理
导读:我正在创建一个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 错误在
我正在创建一个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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |