1

我是 AngularJs 的新手,在下面的代码中遇到了麻烦。

return {
        require: ['^myElement'],
        restrict: 'EA',
        replace: true,
        scope: true,
        link: function (scope, element, attrs, ctrls) {
            scope.xa = 'This is xa'
                    scope.$on('form:submit', function() {

                        scope.xb = 'This is xb'
                        var data = $compile( '<p>{{xa}} {{xb}}</p>' )( scope );
                        console.log(data.html()); //result is '{{xa}} {{xb}}', the expressions were not applied
                    });
                }
}

我从日志中得到的输出是'{{xa}} {{xb}}',它应该是

'This is xa This is xb'

这是plunker源代码

4

2 回答 2

1

很可能 angularjs 没有时间运行 $digest 循环并且它没有解释变量,因为如果您将结果附加到 html 元素它可以工作:

http://plnkr.co/edit/N7TfEC1R1qNcPxY6eXNG?p=preview

scope.$on('form:submit', function() {
  scope.xb = 'This is xb'
  var data = $compile( '<p>{{xa}} {{xb}}</p>' )( scope );
  element.append(data);
});
于 2015-04-24T03:40:32.757 回答
0

我有一个模式对话框来显示将从模板缓存编译的消息。在我的原始示例中,无论我做什么,它都只是从模板中返回原始字符串。解决方法是我需要将编译代码放入指令的controller部分而不是link部分,然后我将编译后的字符串返回到一个变量中,例如 $scope.data 我将在link

controller: function ( $scope, $element, $attrs ) {

        var vsTemplate = $templateCache.get($attrs.templateUrl)
        $scope.data= $compile(vsTemplate)($scope)
},
link: function (scope, element, attrs, ctrls) {
      dialogs.notify('Errors Summary', $scope.data)
}
于 2015-04-26T18:16:38.793 回答