1

I want to use input fId value in angular controller FollowBtnCtrl, i made a button which called the followMe() function, defined inside the FollowBtnCtrl controller, when i am getting $scope.fId value inside the controller its showing undefined value. Please check my code and tell me where i am wrong, Sorry for this silly question but i am new in angularjs. Thanks in advance

angular controller:

.controller("FollowBtnCtrl", function ($scope) {
    $scope.followMe = function () {
        alert($scope.fId);
    }
});

Html code:

<div ng-controller="FollowBtnCtrl">
    <ons-toolbar-button>
        <input ng-model="fId" id="fId" type="hidden" value="10" />
        <button ng-click="followMe()" class="followButton button button">
            Hello
        </button>
    </ons-toolbar-button>
</div>
3
  • 3
    ng-model="fId" has no value assigned! Try this jsfiddle.net/6a9usr8w Commented Oct 7, 2015 at 9:57
  • can we use input value 10 which we have already given. Commented Oct 7, 2015 at 10:01
  • 1
    No we can not consider value as model value.. Commented Oct 7, 2015 at 10:03

3 Answers 3

1

You ons-toolbar-button directive creates another scope. You can access the parent followMe(), but the parent can not access that scope's defined variables (fId). Many solutions... here's one:

ng-click="followMe(fId)" and $scope.followMe = function(fId){...}

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

1 Comment

you are right, and your solutions is really helpful and appreciated, thanks
1

You can not give value to fId using value attribute in angular.This is a common mistake in new Angular applications. You don't want to write your values into your HTML on the server if you can avoid it. If fact, if you can get away from having your server render HTML entirely, all the better.

Ideally, you want to send out your Angular HTML templates, then pull down your values via $http in JSON and put them in your scope. But if you want to provide value via html, you can do that using ng-init.

<input ng-model="fId" id="fId" type="hidden" ng-init="fId=10" />

See also:AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

Comments

1

ng-model is used for two way binding, i.e. to change the value of the input.

That's why, what you need to do is remove value attribute of the input and initialize fId inside your controller.

Your input:

<input ng-model="fId" id="fId" type="hidden" />

and your controller:

.controller("FollowBtnCtrl", function ($scope) {
    $scope.fId = 10;

    $scope.followMe = function () {
       alert($scope.fId);
    }
});

Comments

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.