Можно использовать функцию как templateUrl. Официальная документация для $ routeProvider гласит:
templateUrl – {string = | function () =}
- JQuery jQGrid развернуть / свернуть сетку при нажатии на слой с надписью
- Как получить доступ к переменной PHP в JavaScript-коде?
- AES-256-CBC Mcrypt-PHP расшифровка и шифрование Crypto-JS
- Измените эту функцию js так, чтобы она использовала значение, полученное из db вместо значений, указанных в массиве, для генерации опций Select
- Получить сегодня коптовую дату
Официальная документация $ routeProvider
В javascript функция имеет синтаксис:
function() {code here}
Но документация показывает:
function()=
Использование function()=Code Here
не работает. Каков синтаксис использования функции для шаблона url в маршрутизации angularjs?
Если я использую что-то вроде:
when('/Store/:StoreId', { templateUrl: function()=webPages/Stores.php?storeID=' + :StoreId, controller: 'storeParseData'
Это не работает. Я думаю, что URL-адрес соответствует :StoreId
автоматически сохраняется в $routeProvider
. Я пробовал использовать $scope
, $location
и $routeProvider
различными способами без успеха. Я ищу простейший и самый прямой способ передать URL-адрес хэш-кода URL # в templateUrl.
Причина, по которой мне нужно вводить динамическую информацию в templateUrl, заключается в том, что загружаемая страница является файлом PHP
который запускает код PHP при загрузке. Код PHP
извлекает информацию из URL-адреса хэша #. Получение :StoreId
в контроллере мне не поможет. Я хочу, чтобы файл PHP
извлекал данные со стороны server side
а не front end
контроллера JavaScript.
<?php //There are two basic scenarios. 1) Get all Store names to populate the Store List // 2) Get all the postings from a particular user, (store) // If the URL has 'cat=something', then get all the store data // If the URL does NOT have 'cat=something', then get the store data. //Only get the store names if DIV with the store names is empty, otherwise //just get the stores listings. $storeNames = file_get_contents('https://NameOfDataURLHere.com/.json'); //information that was previously put into the URL string ending, is parsed with the following code. $urlPiece = $_SERVER['REQUEST_URI']; echo("url Piece: ".$urlPiece); //find the position of the first character in the URL string with search criteria: 'storeID='. //First the URL is checked for 'storeID='. If 'storeID=' exits in the URL, then the page routing injected 'storeID=' //as a string for an argument to be passed. If no argument was passed, then 'storeID=' string. $posOfEqualSign = strrpos($urlPiece,"storeID="); echo("<br>"); echo("posOfEqualSign: ".$posOfEqualSign); echo("<br>"); //If the string 'storeID=' was found, it's okay to proceed. if (isset($posOfEqualSign) && strlen($posOfEqualSign) > 0) { //the substr function in PHP doesn't need an length designation if you want the default to go to the end of the string. $storeID = substr($urlPiece,$posOfEqualSign + 8); echo("storeID Length: ".strlen($storeID)); echo("<br>"); echo("storeID: " . $storeID); echo("<br>"); } if (isset($storeID) && strlen($storeID) > 3) { //get all listings for the store out of the listings database with the store ID //The store ID was retrieved from the URL. The store ID was put into the URL when the user clicked the store name. $storeListings = file_get_contents('https://NameOfDataURLHere.com/'.$storeID.'/.json'); $listingsDecoded=json_decode($storeListings,true); echo("storeListings: ".$storeListings); echo("<br>"); if (strlen($storeListings) > 1) { foreach ($listingsDecoded as $key => $value) { //$keyValHere = "\"" . $key . "\""; //echo "keyValHere " . $keyValHere; echo"<br><br>"; echo "Level 1 Key: " . $key; echo '<br><br>'; $storeListingsData = array(); foreach($value as $x=>$v) { echo "Level 2 Key: " . $x; echo"<br>"; echo "Lelvel 2 value: " . $v; echo"<br>"; $specificListing = substr($v, 4); $catToGetItemFrom = substr($v,0,3); echo 'The Listing ID: ' . $specificListing; echo"<br>"; echo 'The category: ' . $catToGetItemFrom; if (strlen($catToGetItemFrom) > 0 && strlen($specificListing) > 1) { if (ord($catToGetItemFrom) <= 109) { //ord returns the ASCII value of the first character of a string $whatDB = "NameOfDBHere"; } else { $whatDB = "NameOfSecondDBHere"; } $oneStoreListing = file_get_contents('https://'.$whatDB.'.dataURL.com/'.$catToGetItemFrom.'/'.$specificListing.'/.json'); } else { $oneStoreListing = ""; echo('one store Listing: '.$oneStoreListing); } if (strlen($oneStoreListing) > 1) { //Keep adding single store listings to the array until the loop is done. array_push($storeListingsData, $oneStoreListing); } } } } echo '<br>'; echo('store Names: '.$storeNames); echo('<br>'); echo('one store Listing: '.$storeListingsData); } ?>
на<?php //There are two basic scenarios. 1) Get all Store names to populate the Store List // 2) Get all the postings from a particular user, (store) // If the URL has 'cat=something', then get all the store data // If the URL does NOT have 'cat=something', then get the store data. //Only get the store names if DIV with the store names is empty, otherwise //just get the stores listings. $storeNames = file_get_contents('https://NameOfDataURLHere.com/.json'); //information that was previously put into the URL string ending, is parsed with the following code. $urlPiece = $_SERVER['REQUEST_URI']; echo("url Piece: ".$urlPiece); //find the position of the first character in the URL string with search criteria: 'storeID='. //First the URL is checked for 'storeID='. If 'storeID=' exits in the URL, then the page routing injected 'storeID=' //as a string for an argument to be passed. If no argument was passed, then 'storeID=' string. $posOfEqualSign = strrpos($urlPiece,"storeID="); echo("<br>"); echo("posOfEqualSign: ".$posOfEqualSign); echo("<br>"); //If the string 'storeID=' was found, it's okay to proceed. if (isset($posOfEqualSign) && strlen($posOfEqualSign) > 0) { //the substr function in PHP doesn't need an length designation if you want the default to go to the end of the string. $storeID = substr($urlPiece,$posOfEqualSign + 8); echo("storeID Length: ".strlen($storeID)); echo("<br>"); echo("storeID: " . $storeID); echo("<br>"); } if (isset($storeID) && strlen($storeID) > 3) { //get all listings for the store out of the listings database with the store ID //The store ID was retrieved from the URL. The store ID was put into the URL when the user clicked the store name. $storeListings = file_get_contents('https://NameOfDataURLHere.com/'.$storeID.'/.json'); $listingsDecoded=json_decode($storeListings,true); echo("storeListings: ".$storeListings); echo("<br>"); if (strlen($storeListings) > 1) { foreach ($listingsDecoded as $key => $value) { //$keyValHere = "\"" . $key . "\""; //echo "keyValHere " . $keyValHere; echo"<br><br>"; echo "Level 1 Key: " . $key; echo '<br><br>'; $storeListingsData = array(); foreach($value as $x=>$v) { echo "Level 2 Key: " . $x; echo"<br>"; echo "Lelvel 2 value: " . $v; echo"<br>"; $specificListing = substr($v, 4); $catToGetItemFrom = substr($v,0,3); echo 'The Listing ID: ' . $specificListing; echo"<br>"; echo 'The category: ' . $catToGetItemFrom; if (strlen($catToGetItemFrom) > 0 && strlen($specificListing) > 1) { if (ord($catToGetItemFrom) <= 109) { //ord returns the ASCII value of the first character of a string $whatDB = "NameOfDBHere"; } else { $whatDB = "NameOfSecondDBHere"; } $oneStoreListing = file_get_contents('https://'.$whatDB.'.dataURL.com/'.$catToGetItemFrom.'/'.$specificListing.'/.json'); } else { $oneStoreListing = ""; echo('one store Listing: '.$oneStoreListing); } if (strlen($oneStoreListing) > 1) { //Keep adding single store listings to the array until the loop is done. array_push($storeListingsData, $oneStoreListing); } } } } echo '<br>'; echo('store Names: '.$storeNames); echo('<br>'); echo('one store Listing: '.$storeListingsData); } ?>
<br> <div id="idCatName" style="display: inline"><?php echo $catToGetItemFrom;?></div> <br> <div id="idStoreNames" style="display: inline"><?php echo($storeNames);?></div> <br> <div id="idStoreData" style="display: inline"><?php echo($storeListingsData);?></div>
myApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/Store/:StoreId', { templateUrl: function(params){return 'webPages/Stores.php?storeID=' + params.StoreId;}, controller: 'storeParseData' }). otherwise({ redirectTo:'/Home' }); }]);
.when('/:storeId/private', { templateUrl: function(params) {return 'webPages/Stores' + params.storeId;}, controller: 'storeParseData' })
.when('/Store/:StoreId', { templateUrl: 'path/to/your/template/index.html', controller: 'MyController' })
Затем в MyController
для чтения параметра do
$scope.store_id = $routeParams.storeId;
Пример здесь