简体   繁体   中英

Dynamically create scope variables and ng-models in Angular

I'm using this angular directive to add rating to my Ionic app.

Including two ratings on one page would look like this:

$scope.rating1 = {};
$scope.rating1.rate = 0;
$scope.rating1.max = 5;

$scope.rating2 = {};
$scope.rating2.rate = 0;
$scope.rating2.max = 5;

<rating ng-model="rating1.rate" max="rating1.max"></rating>
<rating ng-model="rating2.rate" max="rating2.max"></rating>

This works well, but I wish to integrate this in an ng-repeat which shows a certain amount of questions.

Something like:

<ion-list ng-repeat="n in notif">{{n.question}}<br />
<rating ng-model="rating{{n.id}}.rate" max="rating{{n.id}}.max">
</rating>
</ion-list>

but that doesn't work.

I'm also wondering how I could "make" the scope vars depending on the amount of question. Right now, I just added

$scope.rating1 = {};
$scope.rating1.rate = 0;
$scope.rating1.max = 5;

$scope.rating2 = {};
$scope.rating2.rate = 0;
$scope.rating2.max = 5;

...

ten times, but can this be dynamic too in Angular?

Update:

I've managed to make the scopes and give them a value using:

        function make_rating_scopes(string, value)
        {
            var the_string = string;
            var model = $parse(the_string);
            model.assign($scope, value);
            $scope.$apply();
        }

but the first part is still a mystery.

You are over-thinking this. Rating can be any object ( {} ). Since your notif is an array of question objects, you can simply add a property to represent the rating. You can also add a property for the max , or use a $scope property if all the max are the same.

For example:

$scope.maxRating = 10;
$scope.notif = [{
  question: "question1",
  rating: 3
}, {
  question: "question2",
  rating: 4
}, {
  question: "question3",
  rating: 5
}, {
  question: "question4",
  rating: 8
}];
<ion-list ng-repeat="n in notif">
  {{n.question}}
  <rating ng-model="n.rating" max="maxRating"></rating>
</ion-list>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM