将变量从当前作用域传递给已编译的指令

sir*_*cco 7 javascript angularjs angularjs-directive angularjs-scope

我正在尝试将当前作用域中的变量传递给通过$ compile服务添加的指令.

我可以将一个字符串传递给child指令,但不传递给实际的对象.

这是场景的小提琴:http://jsfiddle.net/ewx2trvx/2/

HTML:

<section ng-app="myApp" ng-controller="MainCtrl">
    <addbuttonsbutton></addbuttonsbutton>
    <div id="space-for-buttons"></div>
</section>
Run Code Online (Sandbox Code Playgroud)

JS:

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

function MainCtrl($scope) {
    $scope.count = 0;
}

myApp.directive("addbuttonsbutton", function () {
    return {
        restrict: "E",
        template: "<button addbuttons>Click to add buttons</button>"
    }
});

//Directive for adding buttons on click that show an alert on click
myApp.directive("addbuttons", function ($compile) {
    return function (scope, element, attrs) {
        element.bind("click", function () {
            scope.count++;
            angular.element(document.getElementById('space-for-buttons'))
                .append($compile("<alert alert='count'></alert>")(scope));
        });
    };
});

//Directive for showing an alert on click
myApp.directive("alert", function () {
    return {
        template: "<div><button class='btn btn-default'>Show alert # {{count}}</button></div>",
        scope: {
            a: '@alert'
        },
        replace:true,        
        link: function (scope, element, attrs) {
            element.bind("click", function () {
                console.log(scope.a);
                alert("This is alert #" + scope.a);
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

谢谢.

dfs*_*fsq 4

首先,您需要在编译和追加后应用作用域,因为您在摘要循环之外操作 DOM:

element.bind("click", function () {
    scope.count++;
    angular.element(document.getElementById('space-for-buttons'))
        .append($compile("<alert alert='count'></alert>")(scope));
    scope.$apply();
});
Run Code Online (Sandbox Code Playgroud)

然后,由于您正在使用alert='count',因此您需要更改alert指令中的范围配置:

scope: {
    a: '=alert'
},
Run Code Online (Sandbox Code Playgroud)

否则,如果您使用,a: '@alert'则需要将其插入到属性中,如下所示:alert='{{count}}'

最后,由于是双向数据绑定,您可以再分配一个中间基元属性来用作按钮的索引:

myApp.directive("alert", function () {
    return {
        template: "<div><button class='btn btn-default'>Show alert # {{index}}</button></div>",
        scope: {
            a: '=alert'
        },
        replace:true,        
        link: function (scope, element, attrs) {
            scope.index = scope.a;
            element.bind("click", function () {
                alert("This is alert #" + scope.index);
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

演示: http: //jsfiddle.net/ewx2trvx/3/