javascript - 使用指令创建隔离范围

标签 javascript angularjs angularjs-scope

我有一组客户端,显示在表单上,​​它们必须具有单独的范围(每个客户端):

View plunker here .

当然,我希望创建一个具有隔离范围的新指令,不会允许使用如下自定义指令将元素绑定(bind)到 oustide $scope:

<fieldset client="156510">
      <legend>Client 156510</legend>
      <!-- Form elements -->
      </section>
</fieldset>

同样:

angular.module("plunker", [])

  .controller("ClientCtrl", function($scope) {})

  .directive("client", function() {
    return {
      restrict: "A",
      scope: {
        name: "@name",
        client: "=client"
      }
    };
  });

鉴于 ng-repeat 不是一个选项,我如何使用指令隔离任何包含的 HTML 的范围? Angular 文档 seem to suggest this is possible ,但我的实现似乎没有按预期工作。

提前致谢。

最佳答案

在没有 template/templateUrl 的独立作用域的元素上的任何指令实际上都不会获得新的作用域。

这是证据 http://plnkr.co/edit/jXwrtG?p=preview

.directive("client", function() {
    return {
      restrict: "A",
      template: '  ',//notice extra spaces
      replace: true,//notice this
      scope: {
        name: "@name",
        client: "=client"
      }
    };
  });

scope=true 也可以解决您的问题。

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

  .directive("client", function() {
    return {
      restrict: "A",

      scope: true
    };
  });

也正如@imscrb所指出的 transclude = true 也可以,但您必须将 ng-transclude 添加到元素

<fieldset client="156510" ng-transclude>

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

.directive("client", function() {
    return {
      restrict: "A",
      transclude: true,

      scope: {
        name: "@name",
        client: "=client"
      }
    };
  });

关于javascript - 使用指令创建隔离范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25168000/

相关文章:

javascript - 隐藏滚动条并使用 CSS 向左向右滑动

javascript - $watchcollection 不适用于模型属性

javascript - ng-swipe-down 和 ng-swipe-up 不起作用

javascript - $scope 上定义的变量直到下一个周期才会更新

javascript - AngularJS 范围未在指令中更新

javascript - addClass 转换不起作用

javascript - setAttribute 样式在 IE 中不起作用

javascript - Angularjs - 对象未传递到指令的范围以进行双向绑定(bind)

javascript - Angular指令充当其他元素的外观的好方法是什么?

javascript - 在angularjs中支持单向绑定(bind)的指令是什么