简体   繁体   English

如何在angular 1.x中动态加载属性指令

[英]How to load attribute directive dynamically in angular 1.x

I am trying to load directive dynamically using values in an object. 我正在尝试使用对象中的值动态加载指令。 To do that I have tried following : 为此,我尝试了以下操作:

<body ng-app="myApp" ng-controller="myCtrl">
    <div {{testDirectiveJson.first}}-directive></div>
    <div {{testDirectiveJson.sec}}-directive></div>
    <div {{testDirectiveJson.third}}-directive></div>
    <script src="./test.directive.js"></script>
</body>

here is my js 这是我的js

var app = angular.module("myApp", []);
 app.controller('myCtrl', function($scope) {
     $scope.testDirectiveJson = {
         first: '1',
         sec: '2',
         third: '3',
     }
     $scope.lastName = "Doe";
 }).directive("1Directive", function() {

     return {
         restrict: 'A',
         template: "<h1>Made by a directive A!</h1>"
     };
 }).directive("2Directive", function() {
     return {
         restrict: 'A',
         template: "<h1>Made by a directive! B</h1>"
     };
 }).directive("3Directive", function() {
     return {
         restrict: 'A',
         template: "<h1>Made by a directive! C</h1>"
     };
 });

but its not working as expected. 但它无法正常工作。 I have lots of condition on which i have to change my view dynamically so I need some way in which i just change in my object and view will react to it. 我有很多条件必须动态更改我的视图,因此我需要某种方式来更改对象,然后视图才能对此做出反应。

please help to get it working. 请帮助使其正常运行。

Try this by creating another directive and dynamically adding the attribute to the elements you need. 通过创建另一个指令并将该属性动态添加到所需的元素来尝试此操作。 JSFIDDLE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM