欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

AngulaJS路由 ui-router 傳參實例

 更新時間:2017年04月28日 08:19:27   作者:D調(diào)12138  
本篇文章主要介紹了AngulaJS路由 ui-router 傳參實例 ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

在這里分享我做的一個使用ui-router 傳參的小demo

1.首先第一步設(shè)置入口文件index.html,注意加載的順序,先加載包,再加載自己寫的控制器。

<!doctype html>
<html lang="en" ng-app="routerApp">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
  <title>測試</title>
  <!--lib是angular包的文件夾-->
  <script src="lib/jquery/jquery-1.11.3.min.js"></script>
  <script src="lib/angular/angular.js"></script>
  <script src="lib/angular-ui/angular-ui-router.js"></script>
  <!--js控制器的文件夾-->
  <script src="js/app.js"></script>
  <script src="js/indexCtrl.js"></script>
  <script src="js/resultCtrl.js"></script>
</head>

<body>

<div ui-view>

</div>

</body>

</html>

2.app.js文件,依賴注入,設(shè)置路由,此處的路由是使用ui-router路由,這里簡單的演示了兩個模板之間的傳參,傳遞參數(shù)的模板test.html和接收參數(shù)的模板result.html

var routerApp = angular.module('routerApp', ['ui.router']);

routerApp.run(function($rootScope, $state, $stateParams) {
  $rootScope.$state = $state;
  $rootScope.$stateParams = $stateParams;
});

routerApp.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/index');
  $stateProvider
    .state('index', {//模板的參數(shù)
      url: '/index',//url的參數(shù)
      templateUrl: 'templates/test.html',//模板的位置
      controller: 'MyController'
    })
    .state('result', {
      url: '/result/:id/:number',//需要傳的參數(shù)的鍵名
      templateUrl: 'templates/result.html',
      controller: 'resultCtrl'
    });
});

3.第一個主頁面的模板test.html,并且設(shè)置點擊事件toResult()

<meta charset="UTF-8">
<div>hello world</div>
<input type="button" ng-click="toResult()" value="toResult">

 4.test.html的控制器indexCtrl.js,設(shè)置需要傳遞的參數(shù)$scope.abc和$scope.toResult,點擊事件toResult()里面其實就是一個$state.go('模板的參數(shù)',{app.js里面需要傳的參數(shù)的鍵名:需要傳的參數(shù)值})的方法

routerApp.controller('MyController', function($scope, $state) {
  $scope.abc = "nice";//需要傳的參數(shù)值
  $scope.def = 10;//需要傳的參數(shù)值
  $scope.toResult = function(){
    $state.go('result',{id: $scope.abc,number: $scope.def});
  }
});

5.接收參數(shù)的模板result.html

<meta charset="UTF-8">
<div>hello world2</div>

6.result.html的控制器resultCtrl.js,這里使用$stateParams的方法去接收上一個頁面?zhèn)鬟f過來的參數(shù)

routerApp.controller('resultCtrl', function($scope, $state, $stateParams) {
  var id = $stateParams.id;
  var number = $stateParams.number;
  console.log(id);
  console.log(number);
});

項目目錄

js\app.js、indexCtrl.js、resultCtrl.js

lib\
jquery\jquery-1.11.3.min.js
angular\angular.js
angular-ui\angular-ui-router.js

templates\test.html、result.html

index.html

其實整個過程并不難,只是穿插在模板和控制器之間,容易讓人摸不著頭腦,只要分清楚具體的參數(shù)是對應(yīng)哪一個,很容易理解。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論