简体   繁体   English

Angular:在范围内更新范围

[英]Angular: update scope inside scope

I have a controller with 2 scopes: 我有2个范围的控制器:

app.controller('search', function($scope) {
    $scope.value1 = '';
    $scope.value2 = 'Some text' + $scope.value1;
}

And an input field: 和一个输入字段:

<input type="text" ng-model="value1">

When I change value1 with the input field (which works), value2 doesn't get updated. 当我使用输入字段更改value1时(有效),value2不会更新。 How can I make this work? 我该如何进行这项工作?

You could follow dot rule while declaring object. 您可以在声明对象时遵循点规则。 That will give you prototypal inheritance thing. 那会给你原型继承的东西。 Both param1 & param2 will refer to the same copy of object. param1param2都将引用对象的相同副本。 So that updating one would update the other one automatically. 这样,更新一个将自动更新另一个。

Markup 标记

<input type="text" ng-model="param1.value">
<input type="text" ng-model="param2.value">

Controller 调节器

app.controller('search', function($scope) {
    $scope.param1 = {value : ''};
    $scope.param2 = $scope.param1;
}

Demo Plunkr Demo Plunkr

Update 更新

If you wanted to keep those variable as primitive then you should have to update them on some event like here you could do it by using ng-change directive 如果您想将这些变量保留为原始变量,则必须在某些事件中更新它们,例如在这里,您可以使用ng-change指令来完成此操作

Markup 标记

<input type="text" ng-model="value1" ng-change="value2 = value1 + ' something'">

Or simply you can move inline html code to you controller function to make it testable. 或者简单地,您可以将内联html代码移至控制器函数以使其可测试。

Markup 标记

<input type="text" ng-model="value1" ng-change="changedValue()">

Code

$scope.changedValue = function(){
    $scope.value2 = $scope.value1 + ' something' 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM