如何在嵌套指令之间共享变量?

时间:2014-11-17 13:14:08

标签: javascript angularjs angularjs-directive angularjs-scope

当一个指令(称为el2)嵌套在另一个指令中(称之为el1)时,我无法访问el1中的“本地声明”变量(例如{{{}}生成的变量来自ng-repeat的1}},ng-init等。

This fiddle demonstrates the issue。代码如下:

el2

如何在var myApp = angular.module('myApp',[]); // define blue `el1` element which contains an `el2` child: myApp.directive('el1', function() { return { restrict: 'E', link: function($scope) { }, replace: true, template: '<div ng-init="value1 = 1;">' + 'value1: {{ value1 }}' + ' <el2></el2>' + '</div>', scope: { } }; }); // define green `el2` element: myApp.directive('el2', function() { return { restrict: 'E', link: function($scope) { }, replace: true, template: '<span ng-init="value2 = 2;">' + 'value1: {{ value1 || "UNDEFINED" }} value2: {{ value2 }}</span>', scope: { value1: '=' } }; }); 指令中访问value1?有没有办法不涉及通过el2函数或link显式修改范围?

1 个答案:

答案 0 :(得分:0)

再次:问题是在两个嵌套指令之间共享一个变量。

解决方案很简单,需要两个半步骤:

  1. 将共享变量的名称作为属性传递给内部(例如my-var="value1"
  2. 将该属性添加到内部指令scope集(例如scope: { myVar: '=' }
    • 请确保您使用dash-delimiting案例作为属性名称(例如my-var而不是myVar
  3. Updated JSFiddle here

    现在,内部指令可以将x.val的外部指令的值作为myValue1来访问。正如所料,绑定是双向的。

    代码:

    var myApp = angular.module('myApp',[]);
    
    var x = {
        val: 1
    };
    
    // define blue `el1` element which contains an `el2` child:
    myApp.directive('el1', function() { 
        return {
            restrict: 'E',
            replace: true,
            controller: function($scope) {
                $scope.x = x;
            },
            template: '<div>' +
                'x.val: {{ x.val }}' +
                ' <el2 my-value1="x.val"></el2>' +
                '</div>'
        };
    });
    
    // define green `el2` element:
    myApp.directive('el2', function() {
        return {
            restrict: 'E',
            replace: true,
            template: '<span ng-init="value2 = 2;">' +
                'myValue1: {{ myValue1 || "UNDEFINED" }} ' +
                '<button ng-click="myValue1 = myValue1+1;">+</button>' +
                'value2: {{ value2 }}' +
                '</span>',
            scope: {
                myValue1: '='
            }
        };
    });
    

    感谢Fabio F.指出可以通过属性简单地传输变量名称。

相关问题