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>
Tushar
  • 85,780
  • 21
  • 159
  • 179
Praveen Rawat
  • 724
  • 2
  • 12
  • 29

3 Answers3

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){...}

oori
  • 5,533
  • 1
  • 30
  • 37
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?

Community
  • 1
  • 1
Deepak Banka
  • 591
  • 1
  • 6
  • 24
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);
    }
});
Jahongir Rahmonov
  • 13,083
  • 10
  • 47
  • 91