I'm using AngularJS 1.3.3 and jQuery 1.11.1.
The following does not bind properly to an ng-repeat (meaning it doesn't bind the DOM to the data or update when the data is updated):
var aliasApp = angular.module('aliasApp', ['ngSanitize']);
aliasApp.controller('AliasController', function($scope) {
$scope.aliases = new Array();
$scope.setAliases = function(v){
var a = new Array();
if (Object.prototype.toString.call(v) === '[object Array]') {
for (var i = 0; i < v.length; i++) {
a.push(new Alias(v[i]));
}
$scope.aliases = a;
}
}
});
Here is the BROKEN code in JSFiddle http://jsfiddle.net/f6njo7sq/
However, putting "aliases" onto the "this" scope does work.
var aliasApp = angular.module('aliasApp', ['ngSanitize']);
aliasApp.controller('AliasController', function($scope) {
var self = this;
self.aliases = new Array();
$scope.setAliases = function(v){
var a = new Array();
if (Object.prototype.toString.call(v) === '[object Array]') {
for (var i = 0; i < v.length; i++) {
a.push(new Alias(v[i]));
}
self.aliases = a;
}
}
});
Here is the WORKING code in JSFiddle http://jsfiddle.net/86wduo52/
Does anyone know why the second one works but the first does not?
The key here is everything to do with how you are approaching $scope.
The JS code you posted is fine. It's your HTML code thats broken.
ng-repeat="alias in root.aliases"
is wrong, instead try
ng-repeat="alias in aliases"
This is because you were looking in the "wrong" scope, the 2nd piece of JS code however changed what $scope your aliases object was in, and instead placed it in the root scope.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments