【发布时间】:2016-08-24 14:58:32
【问题描述】:
我正在从指令中调用控制器函数,但是当我使用 console.log 检查值时,函数参数返回 undefined。想知道我做错了什么,或者我忘记了一步。我实际上对一个值进行了硬编码,以查看它是否显示但仅在控制台中未定义。注意:自定义指令模板来自外部文件,因此函数参数不会传递给控制器。它仅在自定义指令元素附加了值时才有效。应该与内部指令 html 一起使用。
//******************** Directive ********************//
app.directive('customdir', [function() {
return {
restrict: "E",
template : "<div>Get product<button ng-click="addToCart(56)">Add to Cart</button></div>",
scope: {
addToCart:"&"
},
link: function(scope, el, attrs) {
}
};
}]);
//******************** Controller ********************//
app.controller('mycontroller', function($scope) {
$scope.addToCart = function(thumbProductId){
$scope.thumbProductId = thumbProductId;
console.log("thumbProductId =" + $scope.thumbProductId); // Returns Undefined
};
});
//******************** Html ********************//
<html>
<div ng-controller="mycontroller">
<custom-dir add-to-cart="addToCart(thumbProductId)"> </custom-dir>
</div>
</html>
【问题讨论】:
-
在运行时使用 chrome 调试工具检查 thumbProductId 的值。或者干脆注销正在传入的 thumbProductId
-
这个问题是指令外部模板没有返回数据。如果我将值放在自定义指令元素上,它可以工作,但在 html 内部不起作用。
-
现在工作!这就是我需要的。 stackoverflow.com/questions/13318726/…
标签: angularjs angularjs-directive angularjs-scope angular-controller