*请注意:有一个Plunker链接: https://plnkr.co/edit/PAINmQUHSjgPTkXoYAxf?p=preview
首先我想在指令点击事件中传递一个对象作为参数, (这对我来说太复杂了)所以我决定通过分别发送事件和对象来简化它。
在我的程序中,对象在视图控制器中始终未定义,视图本身与Plunker示例相反。
在Plunker示例中,仅在第一个传递事件时控制器上未定义(第二个指令点击事件正常工作)。
HTML
<pick-er get-obj-d="getObj()" obj-d="obj"></pick-er>
查看 - 控制器
function mainController($scope)
{
$scope.test = "work";
$scope.getObj = function(){
$scope.test = $scope.obj;
}
}
指令:
function PickerDirective()
{
return {
restrict: 'E',
scope: // isolated scope
{
obj : '=objD',
getObj: '&getObjD'
},
controller: DirectiveController,
template:`<div ng-repeat="item in many">
<button ng-click="sendObj()">
Click on me to send Object {{item.num}}
</button>
</div>`
};
function DirectiveController($scope, $element)
{
$scope.many =[{"num":1,}];
$scope.sendObj = function() {
$scope.obj = {"a":1,"b":2, "c":3};
$scope.getObj();
}
}
}
答案 0 :(得分:2)
我的情况,使用事件会更简单,看看这个Plunker:
https://plnkr.co/edit/bFYDfhTqaUo8xhzSz0qH?p=preview
主控制器
function mainController($scope)
{
console.log("mainCTRL ran")
$scope.test = "work";
$scope.$on('newObj', function (event, obj) {
$scope.obj = obj;
$scope.test = obj;
});
}
指令控制器
function DirectiveController($scope, $element)
{
$scope.many =[{"num":1,}]
$scope.sendObj = function() {
$scope.$emit('newObj', {"a":1,"b":2, "c":3} )
}
}
return {
restrict: 'E',
controller: DirectiveController,
template:'<div ng-repeat="item in many"><button ng-click="sendObj()">Click on me to send Object {{item.num}}</button></div>'
}