Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 附加到元素父级的模板上的隔离范围_Angularjs_Angularjs Directive_Angularjs Scope - Fatal编程技术网

Angularjs 附加到元素父级的模板上的隔离范围

Angularjs 附加到元素父级的模板上的隔离范围,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,我有以下指示: app.directive("mydirective", ['$compile', function($compile) { function link(scope, element, attrs, ctrl, $transclude) { var actionBtnHTML = `<button type="submit" ng-show="show"></button>`; element.parent().a

我有以下指示:

app.directive("mydirective", ['$compile', function($compile) {
    function link(scope, element, attrs, ctrl, $transclude) {
        var actionBtnHTML = `<button type="submit" ng-show="show"></button>`;

        element.parent().append(actionBtnHTML);

        $compile(element)(scope);
    }

    return {
        restrict: 'A',
        scope: {},
        link: link,
        controller: ['$scope', function MyDirectiveController($scope) {
            $scope.show = true;
        }]
}]);
My指令只是在带有mydirective属性的HTML标记后添加一个按钮

我希望添加的HTML具有与指令相同的作用域,即新的隔离作用域。但在这种配置中并非如此。我猜这是因为添加的HTML在指令HTML标记之外

我的问题是,如何在附加到父元素的模板上应用指令的独立范围?

您可以使用插入额外的HTML内容,同时保持指令的相同范围

directive("mydirective", ['$compile', function($compile) {

  return {
    restrict: 'A',
    scope: {},
    controller: ['$scope', function MyDirectiveController($scope) {
      $scope.show = true;
    }],
    transclude: true,
    template: '<ng-transclude></ng-transclude>' +
      ' <button type="submit" ng-show="show">Submit!</button>'
  }
}])

这是你的指令的一个例子

谢谢你的回答!它工作得很好,但它迫使我将原始HTML标记包装到具有directive属性的div中。不是很重要,但我希望有一个不那么干涉性的指令。实际上,我通过对element.parent而不是element应用$compile方法来解决我的问题。我不知道这是否是正确的方法,但它似乎起了作用。