【问题标题】:Passing a variable to directive from controller on Button click在按钮单击时将变量传递给控制器​​的指令
【发布时间】:2017-03-09 17:37:34
【问题描述】:

TLDR;我不想对两个输入框进行数据绑定,而是将变量从控制器传递给指令(其中有一个控制器)。

目前我有以下

  • HTML 页面
  • HTML 模板
  • Javascript 页面(控制器/指令)

我使用 JS 页面中的指令将模板注入 HTML 页面。

在 HTML 页面中,我在输入框旁边有一个按钮

INITIAL AMOUNT : <input type="text" class="text-right" ng-model="initialAmount">
<button ng-click="clicked()" class="btn btn-success btn-lg" style="margin: 5px;">Add Amount</button>

当我单击按钮时,我希望将输入框中的文本 (initialAmount) 传输到我在指令中创建的另一个输入框(来自模板)。

我尝试过使用$scope.displayArea = $scope.$parent.initialAmount; 在指令中,虽然问题是这是在页面加载时设置的,而不是在单击按钮时设置的。

我也尝试过在指令中使用范围,但没有奏效。

我的指令内部是一个控制器,它包含它执行的所有功能。

谢谢大家!

【问题讨论】:

  • 使用rootScope???还是本地存储?
  • 你需要显示代码,如果可能创建sn -p &lt;&gt;
  • 您尝试做的事情是完全可能的,您能给我们更多的代码吗?
  • 我们需要代码 sn-p 来说明您的尝试。无论如何,对于这种情况,我想到的一件事是使用 $watch(Angular 1)。
  • 谢谢大家,Mamun 的回答很完美

标签: javascript html angularjs angularjs-directive


【解决方案1】:

试试下面的代码:

var myApp = angular.module('myApp', []);
myApp.controller('myController',['$scope', function($scope){
  
}]);

myApp.directive('testDirective', [function () {
    return {
        restrict: 'A',
        template: `In Directive:<br/>
                  <input type="text" ng-model="amount"/>`,
        controller: function($scope){
          $scope.clicked = function(){
            $scope.amount = $scope.initialAmount;
          }
        }
    };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
  In Controller:<br/>
  <input type="text" class="text-right" ng-model="initialAmount"/>
  <button ng-click="clicked()" class="btn btn-success btn-lg" style="margin: 5px;">Add Amount</button>

  <div test-directive></div>
</div>

【讨论】:

  • 完美!多谢了。我认为问题在于我试图在父控制器和指令之间进行拆分,结果变得混乱......
【解决方案2】:

试试这个代码:

var demo = angular.module('demo', []);
demo.directive('secondBox', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: false,
        template: '<input type="text" ng-model="secondTextBox"/>',
        controller:["$scope",function($scope){
            $scope.add=function(){
              $scope.secondTextBox=$scope.firstTextBox;
            }  
        }]
    }});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-app='demo'>
    <div>
      <input type="text" ng-model="firstTextBox"/>
      <button ng-click="add($event)">Add Amount
      </button>
      <second-box></second-box>
    </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 2016-01-11
    • 2021-01-24
    相关资源
    最近更新 更多