2

I am having some problems with angular. Now I have a following code :

<div ng-repeat='item in items'>
            <span>{{item.title}}</span>
            <input ng-change="test()" ng-model='abc'> {{abc}}
            <span>{{item.price| currency}}</span>
            <span>{{item.price * item.quantity| currency}}</span>
            <button ng-click="remove($index)">Remove</button>
        </div>
        <script type="text/javascript" src="libs/angular.min.js"></script>
        <script>
                    function CartController($scope) {
                        $scope.items = [
                            {title: 'Paint pots', quantity: 8, price: 3.95},
                            {title: 'Polka dots', quantity: 17, price: 12.95},
                            {title: 'Pebbles', quantity: 5, price: 6.95}
                        ];
                        $scope.test = function() {
                            console.log($scope.abc);
                        }
                        $scope.remove = function(index) {
                            $scope.items.splice(index, 1);
                        }
                    }
        </script>

I wanna know why I can not console.log abc value in controller? My English is bad, pls help me. Thanks in advance

2 Answers 2

3

Try changing

$scope.test = function() {
     console.log($scope.abc);
 }

to

$scope.test = function() {
     console.log(this.abc);
 }

"this" will resolve to the current scope object and you should be able to print the value as you keep changing the text.

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

3 Comments

@rajasur can you tell why the way he was doing was not working?
@acdcjunior, Each template instance inside ng-repeat gets its own scope (Refer docs.angularjs.org/api/ng/directive/ngRepeat). So what we are having inside of the ng-repeat instance is a childscope of the parent. Using "this" instead of $scope uses the childscope instead of referring to the Parent. If you inspect the variables through a debugger, you will see that the "scope" inside of the ng-repeat templates is actually the child of the parent "$scope" defined in the original code.
oh yeah, sorry I forgot :D. It's perfect answer, thanks again @rajasaur
0

What happens if you declare abc as a variable before trying to use it?

function CartController($scope){
    var $scope.abc = 'foo';
    ...

1 Comment

yes, I tried to declared as you said, but when we invoke console.log($scope.abc); in the test() function and we change input value then the result always is "foo" because controller will not listen the change of input value, what do you think about that @Mee :)? Thank you for relying

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.