2016-08-03 2 views
1

나는 3 개의 변수 ab와 testvar로 구성되어 있으며, testvar는 a와 b의 합입니다. 왜 바인딩이 변수 testvar에 대해 작동하지 않는지 이해하려고합니다. 모델로 입력을 만들었습니다. ab의 초기 값을 사용하여,Angularjs 바인딩 문제

$scope.mymodel.testvar =$scope.mymodel.a+$scope.mymodel.b; 

귀속 a + btestvar에 한 번만이 달성 할 수있는 방법, 어떤 도움을 크게

<!DOCTYPE html> 
<html> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
<body> 

<div ng-app="myApp" ng-controller="myCtrl"> 

<input ng-model="mymodel.a"><br> 
Why this value does ot change on changing input:{{ mymodel.testvar}} 
<br> 
mymodel.a changes on input change: {{mymodel.a}} 
</div> 

<script> 
var app = angular.module('myApp', []); 
app.controller('myCtrl', function($scope) { 
$scope.mymodel={}; 

$scope.mymodel.a=1; 
$scope.mymodel.b=2 
$scope.mymodel.testvar =$scope.mymodel.a+$scope.mymodel.b; 
}); 
</script> 

<p>Test Binding.</p> 

</body> 
</html> 

답변

1

이 줄을 감사합니다.

하나의 솔루션은 다음과 같이 함수로 testvar를 설정하는 것입니다 :

// Javascript 
$scope.getTestVar = function() { 
    return $scope.mymodel.a+$scope.mymodel.b; 
}; 

<!-- HTML --> 
TestVar: {{getTestVar()}} 
1

이유 당신의 mymodel.testvar 당신이 컨트롤러가 처음으로 testvar에 대해 실행할 때 때문에 mymodel.a 또는 mymodel.b가 변경되면 업데이트를하지 않습니다 는 ab의 초기 값의 합으로 계산되므로 testvar은 3과 같습니다. 따라서 변수 testvar은 리터럴 값 3을 저장합니다. 이제 a 또는 b을 변경하여 4 - testvar을 평가합니다. testvar은 여전히 ​​3입니다. testvarmymodel.testvar = function(){ return mymodel.a + mymodel.b};과 같은 함수에 넣으려면이 함수를 호출 할 때 다시 계산해야합니다. 또는 각도로 직접 추가 식에 바인딩 할 수 있습니다. {{mymodel.a + mymodel.b}}

+0

고마워요! 깔끔한 설명 – PortalGuy