【问题标题】:AngularJS : How to access the directive's scope in transcluded content?AngularJS:如何在嵌入内容中访问指令的范围?
【发布时间】:2015-09-18 08:45:19
【问题描述】:

我无法让我的嵌入指令正常工作。我想做以下事情:创建一个指令,输出一个列表,其中每个项目的内容由嵌入的内容定义。例如:

<op-list items="myItems">
  <span class="item">{{item.title}}</span>
</op-list>

所以我会在 op-list 的模板中使用 ng-repeat,并且必须能够访问由 ng-repeat 在转入内容中创建的范围。

这是我到目前为止所做的:

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

myApp.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.myModel = {
        name: 'Superhero',
        items: [{
            title: 'item 1'
        }, {
            title: 'item 2'
        }]
    };
}]);

myApp.directive('opList', function () {

    return {
        template: '<div>' +
            '<div>items ({{items.length}}):</div>' +
            '<div ng-transclude ng-repeat="item in items"></div>' +
            '</div>',
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {
            items: '='
        }
    };
});
<html ng-app="myApp">
  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-controller="MyCtrl">
    <div>Hello, {{myModel.name}}!</div>
    <op-list items="myModel.items"> 
        <span>title: {{item.title}}|{{$scope}}|{{scope}}|{{items}}</span>
    </op-list>
</div>
  
</html>

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    检查这是否有效:

    myApp.directive('opList', ['$scope', function ($scope) {
        return {
            template: '<div>' +
                '<div>items ({{model.items.length}}):</div>' +
                '<ng-transclude ng-repeat="item in model.items"></ng-transclude>' +
                '</div>',
            restrict: 'E',
            replace: true,
            transclude: true,
            scope: {
                items: '='
            }
        };
    }]);
    

    如果没有,则尝试在控制台中检查 $scope 并查看您是否能够访问您的模型。

    【讨论】:

    • 只是将$scope 添加到指令中?这样做,不起作用,请参阅编辑的问题。
    • 你能在控制台中检查 $scope 对象吗?你看到什么了吗?
    • 更正了我的注入机制。我只是想确保 $scope 可用。如果是,那么我们可以继续解决在范围内找到我们的模型的问题。
    • 现在出现错误,尝试运行我的问题中的sn-p来查看。我认为范围尚不可用。我们必须使用链接功能来访问它。
    • 错误...更新sn-p。我看到该对象是可访问的。现在需要弄清楚它什么时候不能使用 ng-repeat...
    猜你喜欢
    • 2014-09-06
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多