Afroza Yasmin Afroza Yasmin - 1 month ago 12
Javascript Question

ng-model not updated from controller to view

in this plunk I have made a demo for my problem which I'm facing from last week. Code snippet contains bootstrap tab which includes two different pages - page1 and page2 and they are using same controller. Page1 has ng-repeat and when we click on option from there then It's hit in controller function vm.edit(selected_variable) and Page2 has a simple input box that has a ng-model="vm.name". My problem is that ng-name is not updated or replaced with the value when vm.edit function updates it. I can solve this problem using rootScope but I don't want to use rootScope. I just want to avoid rootScope and want to use vm.

My code example:

page1:

<div ng-controller="appCtrl as vm">
<div>
<ul>
<li ng-repeat="list in vm.list track by $index">
<button type="button" class="btn-u btn-brd btn-u-none" ng-click="vm.edit(list, $index)" data-toggle="tab" href="#page2">
{{ list.name }}
</button>
</li>
</ul>
</div>
</div>


page2:

<div ng-controller="appCtrl as vm">
<input type="text" ng-model="vm.name">
</div>


Controller:

vm.edit = function(listItem, index) {
vm.name = listItem.name;

console.log(vm.name);
};


The edit function updates vm.name in page1 but it doesn't reflect in page2. Couldn't solve this issue, Any Ideas?

Answer

In order to communicate between controllers, you can make use of $broadcast event to transfer data. Here is the edited Plunker.

Inside vm.edit function register broadcast and listen to the event in the same controller:

vm.edit = function(listItem, index) {
  $rootScope.$broadcast("vm name: changed", listItem.name);
};
$scope.$on("vm name: changed", function(evt, obj){
  vm.name = obj;
});

Also don't forget to add $rootScope dependency to your controller:

app.controller('appCtrl', function($scope, $rootScope) {...});

Note: Here $rootScope is used only to trigger event but not to store the value.

Comments