如何从控制器获取值到指令

时间:2015-07-30 12:34:54

标签: javascript angularjs angularjs-directive

我对angular的指令有疑问。 如何从控制器功能中获取价值,控制器功能是通过我的指令中的ng-click调用的?

这是我的HTML代码:

<tbody data-ng-repeat="car in $data">
    <tr>
        <th><a href="#/detail" ng-click="onShowCarDetails(car)">{{car.Registration}} </a></th>

    </tr>
</tbody>

控制器功能:

module.controller("searchController", [$scope, function($scope){
    $scope.onShowCarDetails = function (car) {
         $scope.car = car;
}

和指令:

directive("searchDirective", [function () {

return {
    restrict: 'AEC',
    scope: {
        onShowCarDetails: '&',
    },
    controller: ["$scope", function ($scope) {
        $scope.onShowCarDetails({car: CAR})
    }],
}

来自searchController的$ scope.car可以获得CAR(指令)信息吗? 或者我可以在diractive中调用函数onShowCarDetails(car)来直接从html获取值吗?如果是这样,那该怎么做?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用$emit$on向父作用域发送和检索数据。

控制器:

function Controller($scope){

    $scope.data = [
        {
            Registration: 'blabla'
        },
        {
            Registration: 'blop'
        }
    ];

    $scope.onShowCarDetails = function (car) {
        //Emit an event
        $scope.$emit('send', car);
    }


}

angular
.module('app.controller', [])
.controller('Ctrl', Controller);

指令:

function searchDirective() {

    function link(scope, elm, attr, ctrl){

        //Listen for event 
        scope.$on('send', function(e, value){
            //Retrieve car value from Controller
            console.log(value);
        });

    }



    var directive = {
        restrict: 'AE',
        templateUrl: 'template.html',
        controller: 'Ctrl',
        link: link
    };

    return directive;

}

angular
    .module('app.directive', [])
    .directive('searchDirective', searchDirective);

template.html:

  <h1>Template</h1>


<table>
  <tr ng-repeat="car in data">
    <td><a href="#/detail" ng-click="onShowCarDetails(car)">{{car.Registration}}</a></td>
  </tr>
</table>

然后,您可以通过调用<search-directive></search-directive>来调用您的指令。

现在,当onShowCarDetails被解雇时,您就可以从指令中检索数据。

相关问题