Scope variable

Here is a code snippet which demonstrate $http in angular js
I am stuck at some part in this code.

$scope.newRule = '';
    $scope.addRule = function () {
        $http.post('/api', { newRule: $scope.newRule })
            .success(function (result) {

                console.log(result);
                $scope.rules = result;
                $scope.newRule = '';

            })
            .error(function (data, status) {

                console.log(data);

            });
    };

in this code does variable newRule needs to be a scope variable ?

$http.post(‘/api’, { newRule: $scope.newRule })

If I understand your question, yes it does because that’s how it’s declared and initialized. An uninitialized variable being passed to $http.post will possibly return unstable results…

An uninitialized variable being passed to $http.post will possibly return unstable results…

no…no …I would initialize …But I want to write this way

$scope.newRule = '';
var someOtherVar= ''; // new variable added. this is not a scope variable.
    $scope.addRule = function () {
        $http.post('/api', { someOtherVar: $scope.newRule }) // Is it a valid code ?
            .success(function (result) {

                console.log(result);
                $scope.rules = result;
                $scope.newRule = '';

            })
            .error(function (data, status) {

                console.log(data);

            });
    };

Is it a valid code ?

comments please

So instead of:

$http.post('/api', { newRule: $scope.newRule })

You are wanting to send an object with a different property, that bing:

$http.post('/api', { someOtherVar: $scope.newRule })

Yes that is valid syntax for JavaScript. The only other thing that you’d need to check is whether the api does anything with that different property name.

but we need a parameter or placeholder to hold data …right ? so I created a new var someOtherVar= ‘’;
and keeping scope bound data there to post

and finally sending

$http.post('/api', { someOtherVar: $scope.newRule })

what is the issue ? why this can not work

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.