javascript - AngularJS 指令调用另一个指令未正确传递数据以使用 $compile 进行渲染

标签 javascript angularjs angularjs-directive angularjs-scope

我正在尝试使用数据驱动指令和带有 $compile 的函数来动态混合数据,我想在其中显示特定数据。

该指令正确调用另一个指令,但它没有传递变量

var fred = [];
$scope.fred = {name:'fred'}

$scope.fred = {name:'fred'}
fred.push('<my-directive data={{fred}} > duh</my-directive>')

$("#directives").append($compile(x)($scope))

另一个指令有

template: '<h1>Whats Up {{fred}}</h1>',

忽略“测试”指令

这是一个jsfiddle http://jsfiddle.net/sm98xx55/

如何将数据从函数 ctrl 传递并渲染到指令“myDirective”?

最佳答案

工作 fiddle - http://jsfiddle.net/es6kppzp/1/

您添加了text里面scopemyDirective这是一个未知的属性(意味着你没有通过)。和模板<h1>Whats Up {{fred}}</h1>应该是<h1>Whats Up {{data}}</h1> 。终于通过了正确的$scopecontroller这样它将传递给您的指令并按您的预期进行绑定(bind)。检查一下,

var module = angular.module('testApp', [])
  .directive('myDirective', function($compile) {
    return {
      restrict: 'E',
      scope: {
        data: '@'
      },
      template: '<h1>Whats Up {{data}}</h1>',
      controller: function($scope, $element) {

      }
    };
  });

function crtl($scope, $compile) {
  var vm = this;
  var fred = [];
  $scope.host = "jimmy";
  $scope.fred = {name:'fred'}
  fred.push('<my-directive data={{fred.name}}> duh</my-directive>')
  fred.push('<my-directive data={{host}}> monkey </my-directive>')
  fred.push('<my-directive data={{host}}> brains </my-directive>')
  fred.push('<my-directive data={{host}}> </my-directive>')
  fred.forEach(function(x) {
    //console.log(x)
    $("#directives").append($compile(x)($scope));
  });
}

关于javascript - AngularJS 指令调用另一个指令未正确传递数据以使用 $compile 进行渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45108439/

相关文章:

javascript - 用循环执行除法

javascript - 无法从 IE 11 中的父页面打印 iframe 内容

twitter-bootstrap - Chrome 中的 AngularJS 和 twitter Bootstrap 编号验证

angularjs - 如何使用 AngularJS 指令中的编译函数来重复服务中的元素

javascript - 为什么当我进入 $scope.variabel 时 ng-click 不工作?

javascript - react typescript : Antd Table filter

javascript - 上传完成后图片不被替换

javascript - 使用 AngularJS 从嵌套的 JSON 中获取值

javascript - Angular ng-options,排序对象

css - 检查正在应用哪个 Bootstrap 类并根据使用 AngularJS 添加行为