Sumant
Sumant

Reputation: 964

How to track the dynamic change in input field value using angularjs

I have an input field which is changing dynamically on some event.

<input name="selectedId" id="selectedId" ng-model="selectedId" type="hidden" on-change="setUrl">

Now I want to redirect the page to that id present in input field when ever it changes.

My controller:

var app = angular.module("myApp", []).
  config(function($routeProvider, $locationProvider) {
    $routeProvider.
      when("/a1", { templateUrl: "partials/page1.html"}).
      when("/a2", { templateUrl: "partials/page2.html"}).
      otherwise( { redirectTo: "/a1" });
  });
app.controller("MainCtrl", function($scope, $location) {  
  $scope.setUrl=function($scope){
    if ($scope.selectedId) {
      alert($scope.selectedId);
    }
    else{
     alert("Out of scope"); 
    }
    //$location.path($scope.selectedId);
  };

Here, I am not able to put the input field value in to scope. I'm not even able to trigger setUrl() so that I can redirect the URL.

I'm new to AngularJS so I need to understand the concept.

Upvotes: 0

Views: 3684

Answers (2)

Stewie
Stewie

Reputation: 60396

  1. You are using on-change. AngularJS has a ngChange directive. Use it.
  2. Once you use ngChange also replace setUrl with setUrl().
  3. Then, remove the $scope param from setUrl function signature. $scope is defined inside the MainCtrl so it's implicitly available to all functions defined in it. You don't ned to pass it in.
  4. You are using hidden input to receive the new id from somewhere, only to pass it on to setUrlfunction. You don't need that hidden input. Consider using AngularJS shared services, or event broadcasting, or use $scope.$watch.

Upvotes: 3

Ajay Singh Beniwal
Ajay Singh Beniwal

Reputation: 19037

One possible to your work around is

Register a watch on input model and change location inside that watch function

app.controller("MainCtrl", function($scope, $location) {  
 $scope.$watch('selectedId',function(newvalue,oldvalue){
  $location.path(newvalue);
 }
  };

<input name="selectedId" id="selectedId" ng-model="selectedId" type="hidden" >

Upvotes: 1

Related Questions