2015-01-08 240 views
0

我的指令:使用控制器在指令在AngularJS

angular.module('matrixarMatrice', []).directive('mtxMatriceForm', function() { 
    return { 
    restrict: 'E', 
    templateUrl: 'views/matrice/matrice.html', 
    scope: { 
     matrix: '=', 
     isclicked: '=', 
     selectedprice: '&' 
    }, 
    link: function (scope, element, attrs) { 
     ... 
     scope.selected = function (prices) { 
     scope.selected.id = prices.id; 
     scope.selectedprice(prices); 
     }; 
    } 
    }; 
}); 

我的控制器:

$scope.selectedprice = function (prices) { 
    console.log(prices); 
}; 

我的html:

<mtx-matrice-form matrix="matrix " isclicked="isclicked" selectedprice="selectedprice(prices)"></mtx-matrice-form> 

在我的指令中,当我选择物品时,我打电话给我的控制器。 我想利用我的对象价格,但目前我遇到的问题是我的控制器中有undefined。 有没有人知道这样做的正确方法?

+0

不应该这个'selectedprice =“selectedprice(prices)”'是'selectedprice =“selectedprice”'?您的代码将调用'selectedprice(prices)'的_result_绑定到指令的'scope.selectedprice'。 –

回答

0

我发现这个解决方案:

在我的指令:

... 
scope.selected = function (prices) { 
    scope.selected.id = prices.id; 
    scope.selectedprice({prices: prices}); 
}; 
... 
+0

基本上,当你想传递一个函数到指令时,你需要传递参数作为一个对象。所以在你的情况下,它应该是这样的:' 。 – lvarayut

1

这是您可以使用包括指令内部控制器一个选择!还有其他选项。希望能帮助到你!

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

app.controller('MainCtrl', function($scope) { 
    $scope.name = 'Lorem'; 
}); 

app.directive('directives', function() { 
    return { 
    restrict: 'E', 
    controller: function($scope, $element){ 
     $scope.name = $scope.name + "impsum"; 
    }, 
    link: function(scope, el, attr) { 
     scope.name = scope.name + "Ipsum"; 
    } 
    } 
})