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

时间:2013-11-19 15:25:57

标签: javascript angularjs object angularjs-directive

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

<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

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

1 个答案:

答案 0 :(得分:2)

试试这个

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

Working Demo