0

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.

1
  • Its Working for keypress event, But not for the dynamic values through javascript. Commented Jun 18, 2013 at 12:53

2 Answers 2

3
  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.
Sign up to request clarification or add additional context in comments.

Comments

1

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" >

1 Comment

I tried it but its not working. any link. on change its not calling controller function.

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.