AngularJS覆盖了transclude范围的范围

时间:2018-04-01 20:34:31

标签: angularjs angularjs-directive

dir call的初始化:

<div ng-app="myApp">
  <dir arr="[{name: 'Dennis'}, {name: 'Bob'}]">
    <h3>Working as not wanted: {{$parent.obj.name}}</h3>
    <h3>Not working as wanted: {{obj.name}}</h3>
  </dir>
</div>

指令是自我:

angular.module("myApp",[]).directive('dir', function(){
    return {
        restrict: 'E',
        transclude: true,
        scope: {
            arr: '='
        }, 
        template: '<span ng-repeat="obj in arr"><ng-transclude></ng-transclude></span>',
        link: function(scope, iElement, iAttrs, controller, transcludeFn) {
            //transcludeFn(scope);
        }
    }
});

来自带有第一个参数的文档transcludeFn应该替换transclude隔离范围的范围,但它不会。 Here is the codepen working sample to test/work with.

3 个答案:

答案 0 :(得分:1)

ng-transclude将保留内容,因为它是指令元素中的内容,而指令中的那些元素仍然只查找父作用域。

<div ng-app="myApp">
    <dir arr="[{name: 'Dennis'}, {name: 'Bob'}]">
        <h3>Working as not wanted: {{$parent.obj.name}}</h3>
    </dir>
</div>

angular.module("myApp",[]).directive('dir', function(){
    return {
        restrict: 'E',
        transclude: true,
        scope: {
            arr: '='
        }, template: '<span ng-repeat="obj in arr"><ng-transclude></ng-transclude> <h3>Not working as wanted: {{obj.name}}</h3></span>',
        link: function(scope, iElement, iAttrs, controller, transcludeFn) {
            //transcludeFn(scope);
        }
    }
});

您可以查看演示here

答案 1 :(得分:0)

ng-transclude将采用其中存在的scope的{​​{1}}

请检查此指令代码:

directive

<强> HTML

angular.module("myApp",[]).directive('dir', function(){
    return {
        restrict: 'E',
        transclude: true,
        scope: {
            arr: '='
        }, template: '<span ng-repeat="obj in arr"><ng-transclude></ng-transclude></span>',
    link: function(scope, el, attrs, ctrl, transclude) {
      scope.arr = [{name: 'Dennis'}, {name: 'Bob'}];
      transclude(scope, function(clone, scope) {
        // this takes the parent scope
      });
    }
    }
});

Here is a slackblitz for the same

答案 2 :(得分:0)

经过大量研究,我发现,直到现在还没有办法修改translucde的范围。所以我移出了重复,这打破了这个问题的逻辑,并作为临时解决方案,我做了这个。 HTML:

<div ng-app="myApp" ng-controller="app">
  <dir obj="obj" ng-repeat="obj in arr">
    <h3>Looking to get: {{obj.name}}</h3>
  </dir>
</div>

和javascript:

ular.module("myApp", []).controller('app', function($scope){
  $scope.arr = [{name: 'Dennis'}, {name: 'Bob'}];
}).directive('wsort', function(){
    return {
        restrict: 'E',
        transclude: true,
        scope: {
            obj: '='
        }, template: '<ng-transclude></ng-transclude>'
    }
});

我们指定在指令之外重复并在我们需要的地方使用obj。