Reputation: 321
Feel like I'm being a bit brain dead today.
I have a string and an input. I need to pull through the value from the input into the middle of the string. However I'd like it to be binded so as you type in the input you can see it in the string.
One solution would be to spilt the string and then I could do something like.
<p>{{stringStart}} {{country}} {{stringEnd}}</p>
But I will probably be in a situation where the string needs to pull through many vars so spilting it up like this will probably be tedious. See example below.
https://jsfiddle.net/bc3chrog/5/
I feel like there is probably another easier way to do this but can't seem to be able to work out a good solution.
EDIT: Sorry I should mention I need to save the new string back to a scope var. Some people have made some working solutions but I was trying to avoid having the text set it two places. It's cleaner and easier to make an update to it if it is only defined in one place.
Upvotes: 0
Views: 63
Reputation: 7066
If you need the concatenated string in your controller, you can set a $watch
.
$scope.$watch('country', function(newValue) {
$scope.fullCountryString = 'string start ' + newValue + ' string end';
});
Any time $scope.country
gets a new value, a new value will be created for $scope.fullCountryString
. So you can just bind your view to fullCountryString
in as many places as you need it.
Upvotes: 2
Reputation:
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>
Upvotes: 0