草庐IT

javascript - AngularJS - 包装指令

coder 2025-01-11 原文

我似乎对指令中的孤立作用域感到困惑,希望你能帮助我。

我试图将一段代码(其中包含一些自定义指令)包装到一个新指令中以减少代码重复。显然,我需要将一些属性(如 ng-model)作为参数添加到我的新指令中,以使该指令可重用。 ng-model 不喜欢表达式(我首先尝试了 ng-model="{{myVariableWhichContainsDesiredNgModelString}}"),因此我在这篇文章中结束了:AngularJS - Create a directive that uses ng-model

虽然接受的答案似乎适用于简单设置,但我从接受的答案中编辑了 plunker 以测试它是否也适用于嵌套指令:(在我的应用程序中,我需要包装来自第三方的指令 -我无法编辑的库)Plunker。在我的代码中,每个指令似乎都生成了自己的范围,并且通过在范围定义中使用 = 进行双向数据绑定(bind)似乎没有按预期进行。

编辑: 由于不清楚我在问什么,我编辑了上面的 Plunker 并将重新表述问题:在 Plunker 中,我有三个输入字段,它们应该绑定(bind)到同一个模型-值(value)。这最初有效,但一旦我编辑第三个输入字段,它就会在其隔离范围内生成自己的变量,而不是更新初始值。显然,第三个输入字段指的是从那一点开始的新变量。我怎样才能避免这种行为并使输入链接到 $scope.model.name

观察:从模板中删除 isolated-scope-directive 会使一切按预期工作......

template: '<div><my-input ng-model="myDirectiveVar"></my-input></div>',

代替

template: '<div><my-isolated-scope-directive><my-input ng-model="myDirectiveVar"></my-input></my-isolated-scope-directive></div>',

Plunker

HTML:

<!-- this binds to the model which i would like all my inputs to bind to.-->
<input ng-model="name">

<!-- Example 1: This seems to generate a new modelvalue in the isolated-scope directive. Can I avoid this without modifying that directive?-->
<my-isolated-scope-directive><my-input ng-model="name"></my-input></my-isolated-scope-directive>

<!-- Example 2: This is what i would like my code to look like in the end: One directive which uses the code-snippet of Example 1 as template and passes some parameters into that template.-->
<my-wrapper-directive my-directive-var="name"></my-wrapper-directive>

指令:

my-input 包含修改后的输入字段:

app.directive('myInput', function() {
    return {
        restrict: 'E',
        replace: true,
        require: 'ngModel',
        template: '<input class="some">',
        link: function($scope, elem, attr, ctrl) {
            console.debug($scope);
        }
    };
})

my-isolated-scope-directive 是一个占位符指令,它有自己的隔离范围来模拟嵌套指令的行为:

.directive('myIsolatedScopeDirective', function() {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        scope: {
            something: '='
        },
        template: '<div ng-transclude></div>',
        link: function($scope, elem, attr, ctrl) {
            console.debug($scope);
        }
    };
})

my-wrapper-directive 封装了之前的两个指令并接受一个参数,该参数应该用作输入字段的 ng-model 值:

.directive('myWrapperDirective', function() {
    return {
        restrict: 'E',
        transclude: false,
        replace: true,
        scope: {
          myDirectiveVar: '='
        },
        template: '<div><my-isolated-scope-directive><my-input ng-model="myDirectiveVar"></my-input></my-isolated-scope-directive></div>',
        link: function($scope, elem, attr, ctrl) {
            console.debug($scope);
        }
    };
});

如有任何关于我遗漏的建议和提示,我们将不胜感激。我能否以某种方式将 ng-model 链接到服务实例而不使我的指令依赖于该服务?

最佳答案

我不会这样做,因为它是使用作用域的旧符号...我会使用 controllerAs 和 bindToController

脚本:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function() {
  this.model = { name: 'World' };
  this.name = "Felipe";
});

app.directive('myInput', function() {
  return {
    restrict: 'E',
    replace: true,
    // controllerAs: 'app',
    require: 'ngModel',
    template: '<input class="some">',
    controller: function(){

    }
  };
})
.directive('myIsolatedScopeDirective', function() {
  return {
    restrict: 'E',
    transclude: true,
    controllerAs: 'app1',
    bindToController: {
      something: '='
    },
    template: '<div ng-transclude></div>',
    controller: function(){

    }
  };
})
.directive('myWrapperDirective', function() {
  return {
    restrict: 'E',
    transclude: false,
    controllerAs: 'app2',
    bindToController: {
      myDirectiveVar: '='
    },
    template: '<div><my-isolated-scope-directive>'+
      '<my-input ng-model="app2.myDirectiveVar"></my-input>'+
      '</my-isolated-scope-directive></div>',
    controller: function(){

    }

  };
});

索引:

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="style.css">
  <script>document.write("<base href=\"" + document.location + "\" />");</script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as main">
  This scope value 
  <input ng-model="main.model.name">
  <my-isolated-scope-directive>
    <my-input ng-model="main.model.name"></my-input>
  </my-isolated-scope-directive>
  <my-wrapper-directive my-directive-var="main.model.name">
  </my-wrapper-directive>
</body>
</html>

查看插件: http://plnkr.co/edit/VD0wXO1jivQc3JvfQFTh?p=preview

更新 是的,好点,所以如果你想使用 controllerAs,你至少需要 angular 1.2,对于 bindToController,你需要 angular 1.3

关于javascript - AngularJS - 包装指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35015556/

有关javascript - AngularJS - 包装指令的更多相关文章

  1. ruby-on-rails - Cucumber 是否只是 rspec 的包装器以帮助将测试组织成功能? - 2

    只是想确保我理解了事情。据我目前收集到的信息,Cucumber只是一个“包装器”,或者是一种通过将事物分类为功能和步骤来组织测试的好方法,其中实际的单元测试处于步骤阶段。它允许您根据事物的工作方式组织您的测试。对吗? 最佳答案 有点。它是一种组织测试的方式,但不仅如此。它的行为就像最初的Rails集成测试一样,但更易于使用。这里最大的好处是您的session在整个Scenario中保持透明。关于Cucumber的另一件事是您(应该)从使用您的代码的浏览器或客户端的角度进行测试。如果您愿意,您可以使用步骤来构建对象和设置状态,但通常您

  2. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  3. ruby - 在 Mechanize 中使用 JavaScript 单击链接 - 2

    我有这个:AccountSummary我想单击该链接,但在使用link_to时出现错误。我试过:bot.click(page.link_with(:href=>/menu_home/))bot.click(page.link_with(:class=>'top_level_active'))bot.click(page.link_with(:href=>/AccountSummary/))我得到的错误是:NoMethodError:nil:NilClass的未定义方法“[]” 最佳答案 那是一个javascript链接。Mechan

  4. ruby-on-rails - 获取 ActionController::RoutingError(当尝试使用 AngularJS 将数据发布到 Rails 服务器时,没有路由匹配 [OPTIONS] "/users" - 2

    尝试从我的AngularJS端将数据发布到Rails服务器时出现问题。服务器错误:ActionController::RoutingError(Noroutematches[OPTIONS]"/users"):actionpack(4.1.9)lib/action_dispatch/middleware/debug_exceptions.rb:21:in`call'actionpack(4.1.9)lib/action_dispatch/middleware/show_exceptions.rb:30:in`call'railties(4.1.9)lib/rails/rack/logg

  5. javascript - jQuery 的 jquery-1.10.2.min.map 正在触发 404(未找到) - 2

    我看到有关未找到文件min.map的错误消息:GETjQuery'sjquery-1.10.2.min.mapistriggeringa404(NotFound)截图这是从哪里来的? 最佳答案 如果ChromeDevTools报告.map文件的404(可能是jquery-1.10.2.min.map、jquery.min.map或jquery-2.0.3.min.map,但任何事情都可能发生)首先要知道的是,这仅在使用DevTools时才会请求。您的用户不会遇到此404。现在您可以修复此问题或禁用sourcemap功能。修复:获取文

  6. ruby-on-rails - 我将 Rails3 与 tinymce 一起使用。如何呈现用户关闭浏览器javascript然后输入xss? - 2

    我有一个用Rails3编写的站点。我的帖子模型有一个名为“内容”的文本列。在帖子面板中,html表单使用tinymce将“content”列设置为textarea字段。在首页,因为使用了tinymce,post.html.erb的代码需要用这样的原始方法来实现。.好的,现在如果我关闭浏览器javascript,这个文本区域可以在没有tinymce的情况下输入,也许用户会输入任何xss,比如alert('xss');.我的前台会显示那个警告框。我尝试sanitize(@post.content)在posts_controller中,但sanitize方法将相互过滤tinymce样式。例如

  7. ruby - 使用 Selenium WebDriver 启用/禁用 javascript - 2

    出于某种原因,我必须为Firefox禁用javascript(手动,我们按照提到的步骤执行http://support.mozilla.org/en-US/kb/javascript-settings-for-interactive-web-pages#w_enabling-and-disabling-javascript)。使用Ruby的SeleniumWebDriver如何实现这一点? 最佳答案 是的,这是可能的。而是另一种方式。您首先需要查看链接Selenium::WebDriver::Firefox::Profile#[]=

  8. ruby - Watir-Webdriver 是否支持点击目标为 javascript 的链接? - 2

    我是Ruby和Watir-Webdriver的新手。我有一套用VBScript编写的站点自动化程序,我想将其转换为Ruby/Watir,因为我现在必须支持Firefox。我发现我真的很喜欢Ruby,而且我正在研究Watir,但我已经花了一周时间试图让Webdriver显示我的登录屏幕。该站点以带有“我同意”区域的“警告屏幕”开头。用户点击我同意并显示登录屏幕。我需要单击该区域以显示登录屏幕(这是同一页面,实际上是一个表单,只是隐藏了)。我整天都在用VBScript这样做:objExplorer.Document.GetElementsByTagName("area")(0).click

  9. 网页设计期末作业,基于HTML+CSS+JavaScript超酷超炫的汽车类企业网站(6页) - 2

    🎉精彩专栏推荐💭文末获取联系✍️作者简介:一个热爱把逻辑思维转变为代码的技术博主💂作者主页:【主页——🚀获取更多优质源码】🎓web前端期末大作业:【📚毕设项目精品实战案例(1000套)】🧡程序员有趣的告白方式:【💌HTML七夕情人节表白网页制作(110套)】🌎超炫酷的Echarts大屏可视化源码:【🔰Echarts大屏展示大数据平台可视化(150套)】🔖HTML+CSS+JS实例代码:【🗂️5000套HTML+CSS+JS实例代码(炫酷代码)继续更新中…】🎁免费且实用的WEB前端学习指南:【📂web前端零基础到高级学习视频教程120G干货分享】🥇关于作者:💬历任研发工程师,技术组长,教学总监;

  10. ruby-on-rails - 在页面的最底部包含 javascript 文件 - 2

    我有一个Rails应用程序。还有一个javascript(javascript1.js)文件必须包含在每个View的最底部。我把它放在/assets/javascripts文件夹中。Application.js包含以下代码//=requirejquery//=requirejquery_ujs//=someotherfiles//=require_directory.即使Application.js中不包含javascript1.js,它也会自动包含,不是吗?那么我怎样才能做我想做的事呢? 最佳答案 单独定义、包含和执行您的java

随机推荐