如何将`controllers`状态传递给`directive`模板函数?

时间:2015-06-25 11:34:39

标签: angularjs

根据当前页面,我需要更改模板。我的问题是,如何将current页面从controller传递到directives模板方法?

这是我的尝试:

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

myApp.controller('main', function ($scope) {

    $scope.template = "homePage";

});

var getTemplate = function (page) { //i need $scope.template as params

  if (page == "homePage") {
    return "<button>One Button</button>"
  }

  if (page == "servicePage") {
    return "<button>One Button</button><button>Two Button</button>"
  }

  if (page == "homePage") {
    return "<button>One Button</button><button>Two Button</button><button>Three Button</button>"
  }

}

myApp.directive('galleryMenu', function () {

  return {

    template : getTemplate(template), //$scope.template need to pass

    link : function (scope, element, attrs) {

      console.log(scope.template); 

    }

  }

})

Live Demo

更新

我正在尝试这样,但仍然会出错。将$route注入directive的正确方法是什么?

var galleryMenu = function ($route, $location) {

    return {

        template : function () {

            console.log($route.current.className); //i am not getting!

        },

        link : function () {



        }

    }

}

angular
    .module("tcpApp", ['$route', '$location'])
    .directive('galleryMenu', galleryMenu);

2 个答案:

答案 0 :(得分:1)

您可以在指令声明中调用$routeParams,以便在template函数中使用它。

myApp.directive('galleryMenu', ['$routeParams', function($routeParams) {
    return {
        template: function () {
            var page = $routeParams.page || 'homePage', // Define a fallback, if $routeParams doesn't have 'page' param
                output;

            switch (page) {
                case "servicePage":
                    output = "<button>One Button</button><button>Two Button</button>";
                    break;

                default:
                case "homePage":
                    output = "<button>One Button</button>";
                    /*
                    NOTE: Or this other, it was confusing to tell which one to use
                    output = "<button>One Button</button><button>Two Button</button><button>Three Button</button>";
                    */
                    break;
            }

            return output;
        },
        link: function(scope, element, attrs) {
            /* ... */
        }
    }
}]);

编辑1:

如果您使用ui-router$routeParams切换到$stateParams

答案 1 :(得分:0)

您需要从$ state.current获取当前网址,并且可以在templateProvider的帮助下传入指令。

myApp.directive('galleryMenu', function () {

  return {

    templateProvider : getTemplate(template), //$scope.template need to pass

    link : function (scope, element, attrs) {

      console.log(scope.template); 

    }

  }
来自getTemplate的

可以返回$ state.current。希望如此,它会帮助你。