来自控制器的指令模板

时间:2016-07-21 21:34:33

标签: javascript angularjs typescript ecmascript-6

我试图根据它的控制器变量在模板中加载指令。我在这里看到的其他问题依赖于传递给指令的字符串而不是从控制器中获取它。

指令:

import {LanguageController} from "./language.controller.ts";

export class LanguageSelectDirective {
    static NAME: string = "selectLanguage";


    static factory(): ng.IDirective {

        let directive = {
            restrict: "E",
            link: function() {},
            templateUrl: function(elem, attrs){
                return "./" + attrs.language + "/language.html"
            },
            scope: {
                language: "@"
            },
            controller: LanguageController,
            controllerAs: "lc",
            bindToController: true
        };

        return directive;
    }
}

控制器:

export class LanguageController{
   private selectedLanguage: String;
   //More stuff
}

模板:

<select-language ng-hide="authenticated" language="{{lc.selectedLanguage}}"></select-language>



我一直看到的错误是:

GET http://localhost:3000/%7B%7Blc.selectedLanguage%7D%7D/language.html 404 (Not Found)

如何强制它将语言参数评估为控制器变量而不是文字字符串?

2 个答案:

答案 0 :(得分:0)

尝试

<select-language ng-hide="authenticated" language="lc.selectedLanguage"></select-language>

...你不需要{{}}花括号

这是一个使用角度1.4的http://plnkr.co/edit/HOjKKm

的plnkr

这是指令功能:

let directive={
  return {
      restrict: 'E',
      scope: {
        language: '=', //= not @ ensures the model value is interpreted
        'content': '=' //we are binding to an object
      },
      template:  '<ng-include src="getTemplateUrl()"></ng-include>',
      controller: function($scope){
        $scope.getTemplateUrl=function(){
          return $scope.language+'_language.html';
        }
      }
    }
}

答案 1 :(得分:0)

不要在指令定义中使用{{}},也请在范围定义中使用'='。

<select-language ng-hide="authenticated" language="lc.selectedLanguage"></select-language>