Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs dynamically create models

I'm looping through a result set and dynamically creating model values, such as:

     angular.forEach(users, function(user) {
           $scope.usersModels.online[user.id] = 0;
           $scope.usersModels.online[user.id]['checked'] = 'checked';
           $scope.$watch('usersModels.online[user.id]', function(val) {
                  console.log(val);

           });
     });

I'm also trying to watch the change of these models and get the value. This doesn't work however, any ideas what's wrong?

Thanks!

EDIT:

angular.forEach(users, function(user) {
       $scope.usersModels.online[user.id] = {};
       $scope.usersModels.online[user.id]['value']   = 0;
       $scope.usersModels.online[user.id]['checked'] = 'checked';
       $scope.$watch(function() {
            return $scope.usersModels.online[user.id]['value'];
       }, function(val) {
            console.log(val);
       });
 });
like image 879
dzm Avatar asked Nov 28 '25 03:11

dzm


1 Answers

The code you provided does not give us a complete picture. Some of the missing pieces are:

  • The code for populating the users object
  • The view code that shows how you bind the inputs to the models

Hence, I need to make some assumptions:

  • The code for populating the users object is not the cause of the problem.
  • The input that binds to the checked property is a checkbox.

With the assumptions in mind, one immediate problem I find in your code is that you assign a string value, "checked", to the checked property when you should be using a boolean value. Two-way binding for checkbox input works with boolean value only.

Since I don't get to see the complete picture, it's hard for me to say if that's the only problem with your code. Based on the information you have given, I created a working plunkr. Note that I simply assigned an object of three user ids to generate the users object with the assumption made above. Compare it to your code and identify other possible problems, if any. Please be sure to report back if you found other errors in your code, as it might do good for new comers.

like image 88
tamakisquare Avatar answered Nov 30 '25 16:11

tamakisquare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!