我是使用Angular的新手,我遇到了一个试图将函数调用绑定到隔离范围的问题。我的指令与此
类似angular.module("myApp",[])
.directive("myDirective", function () {
return {
restrict: "A",
scope: {
scopefunc: "&"
},
link: function(scope, elem, attrs){
var myvar=5;
scope.handleButton = function(){
scope.scopefunc(myvar);
}
}
};
}).controller("myController", function ($scope) {
$scope.scopefunc = function(ID){
alert(ID);
};
});
代码适用于某一点。如果发生了scope.handleButton操作,它会正确调用主控制器作用域上的$ scope.scopefunc但是参数myvar不会传递给主作用域 - 它是未定义的。有人能告诉我如何将这个参数传递回主范围吗?
答案 0 :(得分:0)
<div ng-app="myApp">
<div ng-controller="myController">
<div my-directive scopefunc="scopefunc(id)"></div>
</div>
</div>
angular.module("myApp",[])
.directive("myDirective", function () {
return {
restrict: "A",
scope: {
scopefunc: "&scopefunc"
},
link: function(scope, elem, attrs){
var myvar=5;
scope.scopefunc({ id: myvar });
}
};
}).controller("myController", function ($scope) {
$scope.scopefunc = function(ID){
alert(ID);
};
});
<强> DEMO 强>