Using directives inside directives causes binding

2019-09-05 06:36发布

We're using Angular and we're having trouble with resolving variables in directives. This fiddle shows our issue:

Here's the full code: http://jsfiddle.net/VX5LE/65/

//data-translate should handle the translating of the useableButton text
app.directive('window', ['translateService', function (translateService) {

    return {
        restrict: 'E',
        transclude: true,
        scope: {
            useableButtons: '='},
        replace: true,
        template:
                '<div>' +
                    '<button data-ng-repeat="useableButton in useableButtons" data-translate>{{useableButton}}</button>' +
            '</div>'
    };
}]);

I have seen some answers that solve this by:

  1. Using a filter to translate these. - That is actually our current solution but that hinders us with different functionality.

  2. Attaching watches in the controller. - We actually want to avoid watches in our controllers as it makes the code quite dirty if you have a lot of them.

Preferably I would like to see a solution that resides inside of the translate directive without cluttering the controllers.

1条回答
做个烂人
2楼-- · 2019-09-05 07:10

You can do this by interpolating the values manually, then parsing it with the $eval function of the desired scope.

Here is the fiddle: http://jsfiddle.net/VX5LE/66/

The code of the translate-directive:

app.directive('translate', ['translateService', '$interpolate', function (translateService, $interpolate) {
  return {
      restrict: 'A',
      link: function (scope, element, attrs) {
          var pHTML = element.html();
          var parsed = $interpolate(pHTML);
          var translated_result = translateService.translate(scope.$eval(parsed));
          element.text(translated_result);
      }
  }
}]);
查看更多
登录 后发表回答