0

The code below changes an input value from 100 to 200 using Angular. When using my controller to change the value of an input box I am getting a TypeError.

<div ng-controller="FooController" ...>
      <input ng-model="foo.price" type="text" name="price"  class="price" id="price-min" ng-init="foo.price = '100'" />
    ...
    </div>

Controller:

Foobar.controller('FooController', ['$scope', function ($scope) {

setPrice($scope);


function setPrice($scope) {
var price = '200';
    $scope.foo.price = price;

}]);

error:

TypeError: Cannot set property 'price_min' of undefined

I can provide additional code or information if needed

2
  • 1
    can u post a fiddle.. Commented Jun 26, 2015 at 16:58
  • 1
    do not use $scope in this way function setPrice($scope){...} Commented Jun 26, 2015 at 17:01

3 Answers 3

1

I think you want this:

Html-Code:

<div ng-controller="FooController">    
<input ng-model="foo.price" type="text" name="price"  class="price" id="price-min"  ng-init="foo.price = '100'"/>

Angular-Code:

var Foobar = angular.module('testapp', []);

Foobar.controller('FooController', ['$scope', function($scope) {

    $scope.foo = {};
    setPrice($scope);

    function setPrice($scope) {
       $scope.foo.price = "400";
    }
}]);

The problem is that you don't have foo, yet. This is similar to writing

function test(){
    i=123;
}

See what's missing?

However when running this, the ng-init comes after the controller's instantiation. That means you're input has the value 100

In Order to understand, please provide more information what you want to achieve (why the change?)...

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

Comments

1

Try modifying the controller as:

Foobar.controller('FooController', ['$scope', function ($scope) {

$scope.setPrice = function() {
    $scope.foo = {'price': 200};
    return $scope.foo.price;
}
$scope.setPrice();

}]);

2 Comments

I am getting $scope.setPrice(); is not a function when doing this
Its not that it didn't work. I was looking for hogans solution
0

I think you're trying to do this

HTML

<div ng-controller="setPrice">
   <input ng-model="foo.price" type="text" name="price"  class="price" id="price-min" ng-init="foo.price = '100'" />

    <br/><br/>

  Hello, {{foo.price}}!
</div>

JS

var myApp = angular.module('myApp',[]);

setPrice($scope);

function setPrice($scope) {
    var price = '200';
    $scope.foo = {
        price : price
    };
}

The error was the way you declare your $scope.foo

Here the example in JSFiddle

1 Comment

Why can't I just use $scope.foo.price = price? What if I have multiple attributes like a name $scope.foo.name. Will they get overwritten?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.