2017-09-13 20 views
0

感覺今天我有點腦殘。角度綁定輸入值到另一個變種

我有一個字符串和一個輸入。我需要將輸入中的值拉到字符串的中間。不過,我希望它是綁定的,所以當你輸入輸入時,你可以在字符串中看到它。

一個解決方案是將字符串溢出,然後我可以做類似的事情。

<p>{{stringStart}} {{country}} {{stringEnd}}</p> 

但我可能會在該字符串需要通過許多瓦爾拉這麼spilting它像這將可能是乏味的情況。看下面的例子。

https://jsfiddle.net/bc3chrog/5/

我覺得有可能是用另一種更簡單的方法,但似乎沒有能夠制定出一個好的解決方案。

編輯:對不起,我應該提到我需要將新字符串保存回範圍變種。有些人已經提出了一些有效的解決方案,但我試圖避免將文本設置爲兩個地方。如果僅在一個地方定義它,則更新更簡單,更容易。

回答

2

如果你需要在你的控制器的連接字符串,你可以設置一個$watch

$scope.$watch('country', function(newValue) { 

    $scope.fullCountryString = 'string start ' + newValue + ' string end'; 

}); 

任何時候$scope.country得到一個新的價值,新的值將$scope.fullCountryString創建。所以你可以在你需要的地方將你的視圖綁定到fullCountryString

+0

這可能是最好的解決方案!謝謝! –

0

function ExampleController($scope) { 
 
    $scope.countryPlaceholder = 'INPUT TEXT HERE'; 
 
    $scope.countryText = 'I come from ' + $scope.country + '. The best place in the world.' 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app> 
 
    <form ng-controller="ExampleController"> 
 
     <input type="text" class="textbox" name="country" id="country" ng-model="country" placeholder="{{countryPlaceholder}}" /> 
 
     <p>{{'I come from ' + country + '. The best place in the world.'}}</p> 
 
    </form> 
 
</div>

+0

這是我一直在尋找的行爲,但我試圖避免讓文字設置它兩個地方。有沒有辦法解決這個問題,或者我只需要複製文本 –

+0

@MikeYoung沒有問題,您的解決方案首先問題:-) – 2017-09-13 16:17:55

相關問題