angularjs - ng-repeat overrides property in function but not in view model -


i new angular , have problem using custom directive ng-repeat. want display posts rest interface , use _id property inside directive other purposes. however, turns out property 1 last displayed post when used inside function (test in sample below). when trying display id directly on viewmodel shows right one. hope makes sense. appreciated.

//directive.js  angular.module('app').directive('gnpost', mygnpost);  function mygnpost() {     return {         restrict: 'e',         controller: 'postctrl',         controlleras: 'postctrl',         bindtocontroller: {             post: '='         },         scope: {},         templateurl: 'template.html'     }; };  //controller.js  angular.module('app').controller('postctrl', mypostctrl);  function mypostctrl(postrestservice) {     vm = this;     vm.test = function () {         return vm.post._id;     }; };  // template.html  <p>{{postctrl.post._id}}</p> //displays right id  <p>{{postctrl.test()}}</p> //displays id of last element of ng-repeat  //parent page.html  <gn-post ng-repeat="singlepost in posts.postlist" post="singlepost"></gn-post> 

in controller, have following line:

vm = this; 

it should be:

var vm = this; 

by omitting var, there vm variable created on global scope instead of local 1 per controller instance. result each iteration when vm.test called, it's pointing @ function defined on last controller.

fiddle - try including/omitting var in postctrl

it's practice use strict mode in javascript prevent issue , others. in strict mode, impossible accidentally create global variables, doing throw error , you'll see problem straight away. need add line @ start of file or function:

"use strict"; 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -