2017-03-09 119 views
0

TLDR;我不想绑定两个输入框,而是将变量从控制器传递给指令(里面有一个控制器)。将按钮上的变量传递给来自控制器的指令单击

目前我有以下

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

我注入模板到用一个指令的HTML页面JS页面。

在这里,在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; ,但问题在于,当页面加载时单击此按钮时会设置此问题。

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

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

谢谢堆!

+0

使用rootScope ???或本地存储? –

+0

你需要显示代码,如果可能的话创建代码片段<<>' – Satpal

+0

你试图做的事情是完全可能的,你能给我们多一点你的代码吗? – remib

回答

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>

+0

完美!感谢堆。我认为问题在于我试图在父控制器和指令之间分割东西,它只是变得杂乱...... – Ch4osCosmo

0

尝试此代码:

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>

相关问题