我是Angular的新手。这是一个非常简单的问题 - 在我的index.html中,我在两个文本框中定义了两个模型: -
<html><head><script...></head><body ng-app="myApp"ng-controller="MainController" >
<input ng-model="tb1" type="text" name="numberofusers"/>
<input ng-model="tb2" type="text"></input>
</body></html>
在我的app.js中我定义了这个
var app = angular.module('myApp', []);
app.controller('MainController', ['$scope', function($scope){
$scope.tb1 = $scope.tb2;
}]);
现在,我想要的是,无论我在第一个文本框中输入什么(tb1),自动键入第二个文本框(tb2),反之亦然,但这种情况不会发生。
有什么猜测吗?
答案 0 :(得分:1)
您在控制器$scope.tb1 = $scope.tb2;
中的代码只会执行一次(当控制器初始化时),这就是它无效的原因。
您需要将输入元素绑定到同一个model
,然后Angular将自动为您处理双向绑定。
<input ng-model="tb1" type="text" name="numberofusers"/>
<input ng-model="tb1" type="text"></input>
或者如果你想为不同的元素使用两个不同的模型,你可以添加一个钩子到input
的{{1}}事件监听器,如
ng-change
然后这两个元素将自动同步。但是您知道,<input ng-model="tb1" type="text" name="numberofusers" ng-change="tb2 = tb1"/>
<input ng-model="tb2" type="text" ng-change="tb1 = tb2"></input>
只能监控用户输入更改,这意味着,如果您以可编程方式更改ng-change
或tb1
,则不会触发tb2
。
在这种情况下,您应该使用ng-change
$scope.$watch
目前超出了您的要求。
答案 1 :(得分:0)
这是因为控制器只执行一次,如果$ scope.tb2中有任何值将分配给$ scope.tb1,但最初它们都是空白的。 所以你需要$观察变化并为彼此分配价值,如: -
$scope.$watch('tb1',function(newVal){
$scope.tb2=newVal;
})
$scope.$watch('tb2',function(newVal){
$scope.tb1=newVal;
})
如果你想在前端管理它,你可以使用像
这样的ng-change指令<input ng-model="tb1" type="text" ng-change="tb2=tb1" name="numberofusers"/>
<input ng-model="tb2" type="text" ng-change="tb1=tb2"></input>
答案 2 :(得分:0)
您可以使用双向绑定来实现这一目标。一个例子是:JSFiddle
创建您的指令:
var app = angular.module('myApp', []);
app.controller("myCtrl", function($scope) {
$scope.myName = 'Carl';
}).directive("myDirective", function() {
return {
restrict: 'AE',
scope: {
twowayBindingProp: '=myName'
}
}
});
通过以下方式绑定它:
<div ng-app="myApp">
<div ng-controller="myCtrl">
<h1>From parent: </h1>
<h3>parentProp2: <input ng-model="myName"></h3>
<div my-directive my-name="myName">
<h1>From child: </h1>
<h3>twowayBindingProp: {{ twowayBindingProp }}</h3>
<h1>Set from child:</h1>
twowayBindingProp: <input ng-model="twowayBindingProp">
</div>
</div>
</div>