【问题标题】:How can I pass a controller's scope property to a custom directive?如何将控制器的范围属性传递给自定义指令?
【发布时间】:2017-06-19 10:00:58
【问题描述】:

基本设置:

我有一个模态表单,其中有一个自定义指令(子元素)。自定义指令是一个按钮。模式也包含一个输入复选框。

最终目标:

只要复选框被“选中”,就应该启用自定义指令/按钮元素。如果复选框未选中,则应禁用自定义指令/按钮。

到目前为止我所拥有的也就是我的思考过程:

在“modalController”中,我在复选框输入上放置了一个 ng-model,以动态更改变量的值 (isChecked)。当输入被选中时,它会将 $scope.isChecked 值设置为 true,当它未选中时,$scope.isChecked 为 false。

为了禁用按钮,我会将 modalController 中的“isChecked”值传递给自定义指令,在该指令中,它的值可以放在指令模板内按钮上的 ng-checked 表达式中(见下文) .

问题

当我尝试此解决方案时,控制台日志显示错误消息“未定义 inputCheck”。这会在页面加载后立即发生,因此控制台日志会在用户甚至可以单击复选框之前打印出来。关于如何使这项工作的任何想法?

模态html:

  <div ng-controller= "modalController">
    <input type="checkbox" ng-model="isChecked">
    <button-directive inputCheck="isChecked"></button-directive>
  </div>

ButtonDirective.js:

angular.module('starter').directive('buttonDirective', function ($uibModal) {
    return {
        restrict: "EA",
        templateUrl: "app/directives/button-directive.html",
        scope: {
          inputCheck: "@"    
        },
        controller: ['$scope', function ($scope) { 
                  console.log(inputCheck);
         }]
     };
});

button-directive.html:

<button ng-checked="inputCheck">

【问题讨论】:

  • $scope.inputCheck 有效吗?
  • 不,它只是说它未定义
  • 我可以理解为什么投反对票吗?
  • 那不是我。

标签: javascript html angularjs checkbox


【解决方案1】:

你做错了。 $scope 变量与该指令范围声明不同。

每个孩子,包括指令,都在 $scope 范围内,明白吗?

所以你的指令声明不需要那个范围,删除它。

angular.module('starter').directive('buttonDirective', function ($uibModal) {
    return {
        restrict: "EA",
        templateUrl: "app/directives/button-directive.html"
     };
});

还有你的模态,不需要传递你的 inputCheck 属性。

 <div ng-controller= "modalController">
    <input type="checkbox" ng-model="isChecked">
    <button-directive></button-directive>
  </div>

那么你的指令html就变成了

<button ng-checked="isChecked">

看到这个

https://plnkr.co/edit/icaufi3LJxTnbTOkmxdb

【讨论】:

  • 感谢您的回复。即使它是一个子元素,自定义指令也会自动成为一个隔离范围。我必须声明“范围:真实”吗?
  • @Kode_12 不,你没有。让我们试着让你的方式奏效。我会给出另一个答案。
  • @Kode_12 请参阅我在此答案中发布的 plunker
  • 这看起来不错。我只是不知道为什么这在我的代码中不起作用。让我试着复制一下,我会在几个小时内更新你。
【解决方案2】:

按照你的方式工作。

你传递了错误的属性,angularjs 有一个坏事 IMO 就是当你将值传递给像 inputCheck 这样的指令时,你必须用 hiphen 写不同的,所以它需要是input-check

<button-directive input-check="isChecked"></button-directive>

而且你的范围声明必须使用等号

scope: {
  inputCheck: "="    
},

https://plnkr.co/edit/5jlHaE0fvhoDPi2h8XGq?p=preview

【讨论】:

  • @Kode_12 你能做一个 jsfiddle 吗?或者一个笨蛋
  • 我希望,由于客户保密协议的原因,我不能分享我的代码
  • @Kode_12 我明白了。
  • 哇,小错误总是那么容易被忽视!谢谢它现在按预期工作:)
【解决方案3】:

您应该进行以下更改:

<button-directive input-check="isChecked"></button-directive>

scope: {
  inputCheck: "="    
}

<button ng-disabled="inputCheck">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多