【问题标题】:Exposing AngularJS directive property value to parent controller将 AngularJS 指令属性值暴露给父控制器
【发布时间】:2014-11-02 21:37:30
【问题描述】:

我正在开发一个 AngularJS 应用程序。我正在尝试编写一个可重用的组件以在我的整个应用程序中使用。为了演示,我们将只使用一个文本框。我创建了我的attempt here 的小提琴。基本上,我正在尝试使用这样的控件:

<div ng-app="myApp">
  <div ng-controller="myController">
      <my-control textValue="{{controlValue}}"></my-control>
      <br />
      You entered: {{controlValue}}
  </div>
</div>

不幸的是,我无法弄清楚如何在控制器范围和指令范围之间绑定属性。我不确定我在my fiddle 中做错了什么。谁能告诉我我做错了什么?

谢谢!

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您已经创建了具有隔离范围的指令,并且您正在尝试从隔离范围打印值。不对,你可以这样写你的指令,不用隔离scope

     return {
          restrict: 'EAC',
    
            template: '<input type="text" ng-model="controlValue"></input>'
        };
    

    如果你想设置具有隔离作用域的指令,你应该隔离你的作用域,然后使用 $watch 进行更改

    【讨论】:

      【解决方案2】:

      您还没有走远,但使用 {{}} 时需要小心

      去掉大括号,不要对 text-value 属性使用 camelNotation:

      <div ng-app="myApp">
        <div ng-controller="myController">
            <my-control text-value="controlValue"></my-control>
            <br />
            You entered: {{controlValue}}
        </div>
      </div>
      

      使用 ng-model 属性:

      angular.module('ui.directives', []).directive('myControl',
        function() {
          return {
            restrict: 'EAC',
      
            scope: {
                textValue: '='
            },
              template: '<input type="text" ng-model="textValue"></input>'
          };
        }
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-27
        • 1970-01-01
        • 2019-01-22
        相关资源
        最近更新 更多