Angularjs:Javascript函数中没有指令内容

问题描述 投票:0回答:2

我有一个divng-click。当我点击那个div时,它会调用一个从指令中获取脚本内容的函数,然后将其附加到另一个div并访问脚本的内容。但是当我检索指令的内容时,我得到的是指令名而不是内容。我想获得内容。

我打电话的功能:

$scope.someFunction = function(){
  var appendHtml = $compile("<my-custom-directive></my-custom-directive>")($scope);
  $("#someId").append(appendHtml)
  //But when i append I am seeing as <my-custom-directive></my-custom-directive> in html not the actual content

  $(""#someId"").find('script')
}

指示:

app.directive('myCustomDirective', function ($compile) {
  return {
    restrict: 'E',
    templateUrl: '/somecontent.html',
    replace: true,
    link: function ($scope, elem, attr, ctrl) {}
  };
});

Somecontent.html

<script type="text/template">
  <div class="arrow" style="left: 50%;"></div>
    some elements here
  </div>
</script>

我打电话给的HTML:

<div ng-click="someFunction()">
  <div id="someId">
    <my-custom-directive></my-custom-directive> 
    //But Here I am seeing this, when calling 
    $(appendHtml).find('script') in my javascript function, after Javasciprt function call is done, It works fine. But i want to see actual content here when calling $(""#someId"").find('script')
  <div>
</div>
angularjs angularjs-directive
2个回答
0
投票

这不是一个好习惯。

您可以使用ng-if和绑定,如下所示:

HTML

<div ng-click="someFunction()">
  <div id="someId">
    <div ng-if="$scope.isVisible">
          <my-custom-directive></my-custom-directive> 
    </div>
    //But Here I am seeing this, when calling 
    $(appendHtml).find('script') in my javascript function, after Javasciprt function call is done, It works fine. But i want to see actual content here when calling $(""#someId"").find('script')
  <div>
</div>

控制器:

 $scope.isVisible = false;

$scope.someFunction = function(){
   $scope.isVisible = true;
}

您还可以将隔离范围参数传递给您的指令并检查指令模板中的参数


0
投票

您可能只是没有使用jQuery或jqLit​​e来正确选择元素。

您的someFunction可能需要看起来更像这样:

vm.someFunction = function () {
  var appendHtml = $compile('<my-custom-directive></my-custom-directive')($scope);
  angular.element(document).find('some-id-element').append(appendHtml);
};

我把this plunk放在一起,我认为可能会实现你想要做的事情。

这接近你的目标吗?

© www.soinside.com 2019 - 2024. All rights reserved.