Khoga
Khoga

Reputation: 877

AngularJS- change ng-model's value

I am new to AngulatJs(1.4). My Angular script creates two buttons(plus&minus) so that users can increase/decrease product's quantity. It works fine. However, when I click update, it loads the page again and reset quantity to 1($scope.quantity=1;). However, I want to assign the value of <%=product['qty'].to_i%>" to ng-model="quantity". Is it possible ?

var myapp = angular.module("mymodule", []);
myapp.controller('additctl', function ($scope) {
    $scope.quantity = 1;
    $scope.addval = function (val) {
        console.log(val);
        $scope.quantity = val + 1;
    }

    $scope.subval = function (val) {
        if (val > 0) {
            $scope.quantity = val - 1;
        }
    }
});
<form accept-charset="UTF-8" action="change_quantity" method="post">
    <div ng-controller="additctl">
        <button type="button" ng-click=subval(quantity)>-</button>
        <input type="number" ng-model="quantity" value="<%=product['qty'].to_i%>" min="1" max="99" required>
        <button type="button" ng-click=addval(quantity)>+</button>
        <input type="submit" class="btn btn-success" name="button" value="update">
    </div>
</form>

Upvotes: 2

Views: 448

Answers (1)

Cerbrus
Cerbrus

Reputation: 72857

Sure, that's possible. Just set it in the controller:

myapp.controller('additctl',function($scope){
    $scope.quantity = <%=product['qty'].to_i%>;

Make sure you remove the value attribute from the <input>.

If your JS is in a separate file, you can also do this:

  1. Remove $scope.quantity = from your controller.
  2. Set the value like this:
<input type="number" ng-model="quantity"
    ng-init="quantity = <%=product['qty'].to_i%>"
    min="1" max="99" required>

ng-init will run once, when the element is created.

Upvotes: 1

Related Questions