I have below string :
"/root/get";
Now I am generating a query string in above string with 1 scope variable but problem is when the value of that variable change then that new value is not getting update in my URL automatically.
You can see in below demo that I have 2 button Update and Check. In update I am generating query string and on check button I am updating the value of scope variable but that is not getting reflected in my URL.
I am not getting why this is happening.
Expected output when I click on check button without calling generateQueryParameters method:
/root/get?no=2
var app = angular.module("myApp", []);
app.controller("myController", function ($scope) {
$scope.no = 1;
$scope.str = "/root/get";
$scope.update = function (data) {
$scope.str=generateQueryParameters($scope.str,
"no",$scope.no);
console.log($scope.str);
};
$scope.check = function () {
$scope.no=2;
console.log($scope.str);
};
function generateQueryParameters(url,name,value)
{
var re = new RegExp("([?&]" + name + "=)[^&]+", "");
function add(sep) {
url += sep + name + "=" + encodeURIComponent(value);
}
function change() {
url = url.replace(re, "$1" + encodeURIComponent(value));
}
if (url.indexOf("?") === -1) {
add("?");
} else {
if (re.test(url)) {
change();
} else {
add("&");
}
}
return url;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<input type="button" value="Update" ng-click="update()">
<input type="button" value="Check" ng-click="check()">
</div>
Update : I know when the value of $scope.no will change so I don't think I need watcher and I don't want to call generateParameters again.Why angular is not automatically updating the value in my str like the way Angular bindings works?
You need to add watcher for
nowhich call you method calledgenerateQueryParametersand change the value of$scope.strFirst update and then check