AngularJS编译模板并在Showdown扩展中使用它

时间:2015-02-20 07:30:24

标签: angularjs showdown

我试图在我的Angular应用中创建一个Showdown扩展,它将显示范围变量。我能够轻松地设置显示基本范围变量,但现在我想把它放到我可以使用ng-repeat的结果的地方,我无法获得其他任何东西比显示[[object HTMLUListElement]]

到目前为止,这是我的控制人员:

app.controller('MyCtrl', ['$scope', '$window', '$compile', function($scope, $window, $compile){
    $scope.machines = [
        { abbv: 'DNS', name: 'Did Not Supply' },
        { abbv: 'TDK', name: 'The Dark Knight' },
        { abbv: 'NGG', name: 'No Good Gofers'}
    ];
    $scope.machine = $scope.machines[0];

    $scope.machine_list = $compile('<ul><li ng-repeat="m in machines">{{m.abbv}}: {{m.name}}</li></ul>')($scope);
  $scope.md = "{{ machine_list }}";

    var scopevars = function(converter) {
        return [
            { type: 'lang', regex: '{{(.+?)}}', replace: function(match, scope_var){
                scope_var = scope_var.trim();

                return $scope.$eval(scope_var);
            }}
        ];
    };
    // Client-side export
    $window.Showdown.extensions.scopevars = scopevars;
}]);

Plunkr:code so far

我觉得我必须亲近,但现在我不知道我是否在完全错误的轨道上,或者它是否是一个摊牌的东西或者有角度的东西或什么。

1 个答案:

答案 0 :(得分:0)

我意识到我正在按照我这样做的方式与Angular战斗(并且严重失去安静)。控制器中的DOM是禁止的。现在,当我开始正确思考并查看指令时,我有点生气。

现在我没有尝试编译和控制器中的所有内容,而是将$compile服务包含在我使用的指令中,所以:

htmlText = converter.makeHtml(val);
element.html(htmlText);

成为:

htmlText = converter.makeHtml(val);
element.html(htmlText);
$compile(element.contents())(scope);

随着这种变化,我不再需要扩展的部分进行基本评估,因为它被编译{{ machine.name }}会自动转换。

但是这仍然让我无法指定变量来插入模板,只是变量。但是现在输出将通过角度编译我可以将模板放在一个部分并使用扩展来从模式转换为有效的ng-include

新控制器代码:

app.controller('MyCtrl', ['$scope', '$window', '$compile', function($scope, $window, $compile){
    $scope.machines = [
        { abbv: 'DNS', name: 'Did Not Supply' },
        { abbv: 'TDK', name: 'The Dark Knight' },
        { abbv: 'NGG', name: 'No Good Gofers'},
        { abbv: 'TotAN', name:'Tales of the Arabian Nights'}
    ];
    $scope.machine = $scope.machines[0];

  $scope.tpls = {
    'machinelist': 'partials/ml.html'
  };
  $scope.md = "{{machines.length}}\n\n{{include machinelist}}";

    var scopevars = function(converter) {
        return [
          { type: 'lang', regex: '{{include(.+?)}}', replace: function(match, val){
            val = val.trim();
            if($scope.tpls[val] !== undefined){
              return '<ng-include src="\''+$scope.tpls[val]+'\'"></ng-include>';
            } else {
              return '<pre class="no-tpl">no tpl named '+val+'</pre>';
            }
          }}
        ];
    };
    // Client-side export
    $window.Showdown.extensions.scopevars = scopevars;
}]);

当然还有the new plunkr

希望这可以帮助后来的人

wisdom of the ancients