gpt4 book ai didi

javascript - 单击按钮时将变量从 Controller 传递给指令

转载 作者:行者123 更新时间:2023-12-03 04:50:12 26 4
gpt4 key购买 nike

TLDR;我不想对两个输入框进行数据绑定(bind),而是将变量从 Controller 传递到指令(内部有一个 Controller )。

目前我有以下内容

  • HTML 页面
  • HTML 模板
  • Javascript 页面( Controller /指令)

我使用 JS 页面中的指令将模板注入(inject)到 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;在指令中,尽管问题是这是在页面加载时设置的,而不是在单击按钮时设置的。

我也尝试过使用指令中的范围,但没有成功。

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

谢谢!

最佳答案

尝试以下代码:

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>

关于javascript - 单击按钮时将变量从 Controller 传递给指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42689957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com