Reputation: 964
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
Reputation: 60396
on-change
. AngularJS has a ngChange
directive. Use it.setUrl
with setUrl()
.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.id
from somewhere, only to pass it on to setUrl
function. You don't need that hidden input. Consider using AngularJS shared services, or event broadcasting, or use $scope.$watch.Upvotes: 3
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