javascript - updating text on view from ng-repeat -
i have problem updating view using ng-repeat. when click on text, doesnt update overwrites below. (i want have panel names(links) , show description on view) have searched , couldnt find answer or useful me.
html:
<body> <div ng-app="myapp"> <div ng-controller="myctrl"> <ul> <li><a ng-repeat="item in items" ng-click="getinfo(item)" > {{item.name}} <br> </a></li> </ul> </div> <hr> <div ng-controller="myinfo"> <div ng-repeat="info in item" > <h3>name: {{info.name}}</h3> <p> id: {{info._id}}</p> <p> temp: {{info.temp}} </p> </div> </div> </div> </body>
js
var app = angular.module('myapp', []) app.controller('myctrl', function($scope, $http, sharedataservice) { $http.jsonp('data.json').success(function(data) { $scope.items = data; }); $scope.getinfo = function(item) { sharedataservice.additem(item); } }); app.controller('myinfo', function( $scope, sharedataservice ){ $scope.item = sharedataservice.getitem(); }); app.service('sharedataservice', function() { var myitem = []; var additem = function(newobj) { myitem.push(newobj); } var getitem = function(){ return myitem; } return { additem: additem, getitem: getitem }; });
json
angular.callbacks._0([ { "_id": 1, "temp": "asdgdf", "name": "name1" }, { "_id": 2, "temp": "asdasdasd", "name": "name2" }, { "_id": 3, "temp": "asasdasdadgdf", "name": "name3" } ]);
plunker: http://plnkr.co/edit/x65oh0yakrnn8npknfy2?p=preview
you have error in console. add track by
ng-repeat:
<div ng-repeat="info in item track $index">
ng-repeat needs unique id track items in order able update them. if add same item twice, ng-repeat sees same item twice, ans loses mind. using $index (which unique) resolves issue.
keep in mind using $index adequate here, it's preferred use unique id object if can.
edit:
if issue want see 1 element clicked on in view, issue adding item array, when should setting value in service. and, obviously, no need of ng-repeat
in view.
http://plnkr.co/edit/wfg9khcwkmdretftirhr?p=preview
js:
app.controller('myctrl', function($scope, $http, sharedataservice) { //[...] $scope.getinfo = function(item) { sharedataservice.setitem(item); } }); app.controller('myinfo', function( $scope, sharedataservice ){ $scope.$watch(function () { return sharedataservice.getitem(); }, function (value) { $scope.info = value; }) }); app.service('sharedataservice', function() { var myitem; return { setitem: function(newobj) { myitem = newobj; }, getitem: function(){ return myitem; } }; });
html:
<div ng-controller="myinfo" ng-show="info"> <h3>name: {{info.name}}</h3> <p> id: {{info._id}}</p> <p> temp: {{info.temp}} </p> </div>
Comments
Post a Comment