在指令内构建模板字符串

时间:2017-05-17 19:55:19

标签: angularjs angularjs-directive

我正在尝试在指令中构建一串HTML代码,然后将其用作指令的模板。

我尝试了这个,但它不起作用。

Invariant Violation: Could not find "store" in either the context or props of "Connect(Header)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(Header)".

然后我尝试将应用程序的范围传递给指令,但再次出错

myApp.directive('myDirective', [function() {
    return {
        restrict: 'E',
        scope: {
           data: '='      // this is the data that will shape the HTML
        },
        template: str,
        controller: function($scope){
            $scope.str = ****BUILD THE STRING HERE USING 'data'****
        }
    };
}]);

我对如何做到这一点很困惑。在第一个例子中,字符串是正确构建的,当我做

myApp.directive('myDirective', ['$scope', function($scope) {
    var str = ****BUILD THE STRING HERE USING $scope.data****
    return {
        restrict: 'E',
        template: str
    };
}]);

我看到字符串,但很明显,它只是在页面上显示为文本而且不会被解释为HTML代码。

有没有办法在指令的return语句中访问myApp或指令控制器的作用域?

我可以在指令之外构建字符串,但即使我这样做,我仍然无法在指令中访问myApp的范围。

2 个答案:

答案 0 :(得分:1)

如果您没有使用内部范围(或隔离范围)严格定义指令,则指令本质上可以访问外部范围。例如:

&#13;
&#13;
angular.module('app',[]).controller('ctrl', function($scope) {
  $scope.example = {
    message: "Hello world"
  };
}).directive("myDirective", function() {
  return {
    template: '<strong>{{example.message}}</strong>'
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div my-directive></div>
</div>
&#13;
&#13;
&#13;

正如您在上面的示例中所看到的 - 指令&#34;知道&#34;外部范围值,无需实际注入。

现在,您可以创建一个独立的范围,通过这样做,您不会将自己限制在给定的范围内:

&#13;
&#13;
 angular.module('app',['ngSanitize']).controller('ctrl', function($scope) {
  $scope.example = {
    html: "<strong>Hello world</strong>"
  };
}).directive("myDirective", function() {
  return {
    scope: {
      data: '='
    },
    template: '<div ng-bind-html="data"></div>'
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-sanitize.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div my-directive data="example.html"></div>
</div>
&#13;
&#13;
&#13;

通过包含ngSanitize我能够使用ngBindHtml指令并将HTML结构传递给指令内部范围。

答案 1 :(得分:0)

严格地说,通过使用ng-if输出基于控制器中数据计数的不同指令的html,可以实现您尝试做的事情。这是更好的“关注点分离”,因为它意味着您将表示逻辑移动到它所属的视图中,然后您的控制器会关注您的业务逻辑,包括数据计数变量(然后你可以在ng-if中使用。

如果使用这种方法,您将要将数据检索放入控制器使用的服务中,并对两个指令使用相同的控制器。