【问题标题】:AngularJS how to recompile a dynamically loaded directiveAngularJS如何重新编译动态加载的指令
【发布时间】:2015-04-28 01:34:13
【问题描述】:

我整个早上都在搞这个,以隔离我的问题。当我的页面加载时,我正在按名称动态加载指令。现在我希望能够根据 select 选项更改动态加载的指令。

我的 Plunker 的链接如下。它正在正确加载我需要的数据,但没有切换指令。我猜我需要重新编译,但我不知道从哪里开始。

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

这是我的代码的 JavaScript 部分:

  (function(angular) {
  'use strict';

  var myAppModule = angular.module('myApp', []);

  myAppModule.controller('myController', function($scope) {

    $scope.directives = [{
      id: 'my-directive1',
      label: 'My Directive1',
      data: 'Directive 1 data.'
    }, {
      id: 'my-directive2',
      label: 'My Directive 2',
      data: 'Directive 2 data.'
    }];

    $scope.selectedDirectiveId = $scope.directives[0].id;
    $scope.selectedDirectiveData = $scope.directives[0].data;

    $scope.selectChanged = function() {
      for (var i = 0, len = $scope.directives.length; i < len; i++) {
        if ($scope.directives[i].id == $scope.selectedDirectiveId) {
          $scope.selectedDirectiveId = $scope.directives[i].id;
          $scope.selectedDirectiveData = $scope.directives[i].data;
          break;
        }
      }
    };
  });

  myAppModule.directive('loaddirective', function($compile) {
    return {
      restrict: 'A',
      scope: {
        loaddirective: "=",
        directivedata: "="
      },
      link: function($scope, $element, $attr) {
        var value = $scope.loaddirective;
        if (value) {
          $element.html("<div " + value + " directivedata='directivedata'></div>");
          $compile($element.contents())($scope);
        }
      },
      controller: ['$scope',
        function($scope) {
        }
      ]
    };
  });

  myAppModule.directive('myDirective1', function() {
    return {
      templateUrl: 'my-directive1.html',
      scope: {
        directivedata: "="
      }
    };
  });

  myAppModule.directive('myDirective2', function() {
    return {
      templateUrl: 'my-directive2.html',
      scope: {
        directivedata: "="
      }
    };
  });

})(window.angular);

【问题讨论】:

  • 我认为你需要使用 $scope.$watch 来监听值更新,然后改变布局

标签: javascript angularjs


【解决方案1】:

只听变化并更新它。 http://plnkr.co/edit/NuSOA64QJ5Qro3L72zzZ?p=preview

  link: function($scope, $element, $attr) {
    console.log('loaddirective link');
    var value = $scope.loaddirective;

    function update (value) {
      $element.html("<div " + value + " directivedata='directivedata'></div>");
      $compile($element.contents())($scope);
    }
    if (value) {
      update (value);
    }
    $scope.$watch('loaddirective', update);
  },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多