2

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>
3
  • onload it will set $scope value to 1 as you have assigned 1 to $scope.quantity=1; Commented Dec 7, 2015 at 11:50
  • you need to store them in cookies or some type of permanent storage Commented Dec 7, 2015 at 11:50
  • The current value(fetch from database) is in <%=product['qty'].to_i%>, I want to assign it to ng-model="quantity". Commented Dec 7, 2015 at 11:52

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I am using Rails4. I cannot use <%%> inside js file. It gives error.
So, the JS is in a separate file?
Yes, it is in separate file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.