【发布时间】:2015-04-23 18:12:06
【问题描述】:
我正在尝试将一个变量从当前范围传递给通过 $compile 服务添加的指令。
我可以将字符串传递给子指令,但不能传递给实际对象。
这是一个场景:http://jsfiddle.net/ewx2trvx/2/
HTML:
<section ng-app="myApp" ng-controller="MainCtrl">
<addbuttonsbutton></addbuttonsbutton>
<div id="space-for-buttons"></div>
</section>
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);
});
}
};
});
有什么想法吗?
谢谢。
【问题讨论】:
-
你想传递什么?
-
scope.count 变量。
标签: javascript angularjs angularjs-directive angularjs-scope