当前位置: 代码迷 >> JavaScript >> 如何从控制器到指令获取价值
  详细解决方案

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

热度:65   发布时间:2023-06-05 10:24:47.0

我对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获取值吗? 如果是这样,那该怎么办?

感谢帮助。

您可以使用$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>来调用<search-directive></search-directive>

现在,当onShowCarDetails被触发时,您将能够从指令中检索数据。

  相关解决方案