【问题标题】:use a directive with public scope as a isolated scope使用具有公共范围的指令作为隔离范围
【发布时间】:2018-11-27 12:45:54
【问题描述】:

前段时间我写了一个自定义指令,现在在代码中的很多地方都使用它(不能再更改它了)。

它有一个公共范围,直到今天都很好。现在我想在同一个控制器作用域(父作用域)内使用相同的指令两次,但需要每个指令(子作用域)有自己的变量(如隔离作用域)并且彼此不匹配。

是否可以插入此指令并明确声明使用隔离范围,即使它首先是使用公共范围创建的? 或者可能是一种在父控制器内限制它的方法? 或者有没有其他方法可以做到?

例如

// Panel directive
angular.directive('panel', function(){
    return {
        restrict: 'E',
        templateUrl: 'panel.html',
        replace: true,
        transclude: true
    }

});

// Parent directive (include more than one 'panel' directives)
angular.directive('parentDirektive'), function() {
    return {
        restrict: 'E',
        templateUrl: 'parent.html',
        replace: true,
        transclude: true,
        scope: {},
        controller: function($scope) {
            // I want to set different value for this variable
            // in each 'panel' direktive I add in 'parent.html'.
            $scope.headline = 'this.should.be.unique.in.each.panel.directive';
        }
    }
});

父.html

我想以某种方式设置“scope.headline”的值 此处出现的每个面板都不同 (比如隔离每个指令中的变量)?! 但不能在声明中将范围更改为隔离 只有在这种情况下才需要它。

<html>
    <body>
        <!-- I want to display 'Title: First Panel' -->
        <panel></panel>

        <!-- I want to display 'Title: Second Panel' -->
        <panel></panel>
    </body>
</html>

panel.html

<html>
    <body>
        <h1>Title: {{$scope.headline}}</h1>
    </body>
</html>

【问题讨论】:

  • 当询问由您的代码引起的问题时,如果您提供人们可以用来重现问题的代码,您将获得更好的答案。见How to create a Minimal, Complete, and Verifiable example。指令范围可以是 noneinheritedisolate。不清楚您所说的“公共范围”是什么意思。
  • 我用一些例子编辑了我的问题。谢谢

标签: angularjs angularjs-directive angularjs-scope angularjs-controller


【解决方案1】:

例如,最好使用隔离范围。

var myApp = angular.module('myApp');

myApp.directive('myDirective', () => ({
    template: `<div>{{vm.aaa}}</div>`,
    controller: 'myDirectiveCtrl',
    controllerAs: 'vm',
    restrict: 'EA',
    transclude: true,
    scope: {
        aaa: "=" // use if you want to pass varuble to the directive
    },
    bindToController: true,
}));
myApp.controller('myDirectiveCtrl', function () {
    console.log(this.aaa); // will come beck undefind
    vm.$postLink = () => {
        console.log(this.aaa); // return the passed value
    };
});

每个指令都有自己的作用域

<my-directive aaa="'77'"></my-directive>
<my-directive aaa="'99'"></my-directive>

请注意控制器不会在嵌入区域工作

【讨论】:

  • 我在上面的问题中添加了一些示例。问题是我无法将指令的范围更改为“隔离”,因为该指令在更多地方使用(不需要隔离)。我想要的是仅在这种情况下模拟一个类似孤立的范围。
【解决方案2】:

一种选择是为每个组件添加一个控制器:

<html>
    <body>
        <!-- I want to display 'Title: First Panel' -->
        <panel ng-controller="firstPanelController"></panel>

        <!-- I want to display 'Title: Second Panel' -->
        <panel ng-controller="secondPanelController"></panel>
    </body>
</html>

ng-controller 指令创建一个新的继承作用域,控制器可以在该作用域上放置取代父作用域属性的属性。

【讨论】:

    猜你喜欢
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多