将对象作为参数传递给指令

Passing an object to a directive as an argument

本文关键字:指令 参数传递 对象      更新时间:2023-09-26

我有一个视图和一个控制器:

<app-head options="options"></app-head>
app.controller('homeCtrl',function($scope){
  $scope.options = {
    first: {
        description: "A link",
        link: "../"
    },
    second:{
        description: "Another link",
        link: "../../"
    }
  };
});

我想在我的指令中使用对象options

app.directive('appHead',function(){
  return{
    restrict: 'E',
    templateUrl: 'partials/modules/appHead.html',
    replace: true,
    controller: function($scope,$element,$attrs){
      $scope.options = $attrs.options;
    }
  }
});

然而,当我在指令的控制器中调用console.log($scope.options)时,它将返回options No Properties

为什么会这样?我该如何做到这一点?

试试这个

app.directive('appHead',function(){
    return{
        scope: { 
            options: '=', 
        },
        restrict: 'E',
        templateUrl: 'partials/modules/appHead.html',
        replace: true,
        link: function($scope,$element,$attrs){
            // $scope.options 
        }
    }
});

工作演示