Ahmad Elmoualem Ahmad Elmoualem -4 years ago 230
AngularJS Question

Angular: how to concatenate string with $scope value in a controller

what i wanted to do sounds pretty simple but, the result i got is awkward for me.
there is a view with a text filed:

<input colorpicker="hex" type="text" ng-model="item.bgcolor" style="background:{{item.bgcolor}}"/>


In the controller i want to bind the value of the text field and concatenate with string variable like this :

var page = 'hello' + $scope.item.bgcolor + 'world';


the result is
hello undefined world

but if i did
console.log($scope.item.bgcolor);
i get the text field value in the console.
the controller code:

.controller('mainCtrl', function($scope) {
$scope.item = {
bgcolor: $scope.bgcolor,
};

var page = 'hello' + $scope.item.bgcolor + 'world';
$scope.show = function() {
console.log('page', page);
console.log('bgcolor', $scope.item.bgcolor);
};
})


the main view code:

<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<label>Background color</label>
<input colorpicker="hex" type="text" ng-model="item.bgcolor" style="background:{{item.bgcolor}}"/>
<label>Header color</label>
<input colorpicker="hex" type="text" ng-model="item.headercolor" style="background:{{item.headercolor}}"/>
</div>
</div>


app.js:

.state('app.main', {
url: '/main',
views: {
'menuContent': {
templateUrl: 'views/main.html',
controller: 'mainCtrl'
}
}
})

Answer Source

do this .. you don't need to do extra efforts just use watch method and change page value on the change of object ..

watch collection will fire at every change of your item object

$scope.$watchCollection(function(){ return $scope.item ;},function(n,o){
    page = 'hello' + $scope.item.bgcolor + 'world';
});

your controller

.controller('mainCtrl', function($scope) {
 $scope.item = {
    bgcolor: null,
  };

   var page = 'hello' + $scope.item.bgcolor + 'world';

  $scope.$watchCollection(function(){ return $scope.item ;},function(n,o){
       page = 'hello' + $scope.item.bgcolor + 'world';
   });

  var page = 'hello' + $scope.item.bgcolor + 'world';
  $scope.show = function() {
    console.log('page', page);
    console.log('bgcolor', $scope.item.bgcolor);
  };
}) 

Here is the working plunker

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download