Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

javascript - pass a variable into $routeProvider in angular between views? - angularjs

Wondering if there's an 'angular specific' way to try and achieve this. I have a page with some views. When a user clicks an anchor, the views change, simple enough. What I'm curious is, if when the user clicks, is it possible to store a variable (say the span) then pass it to the $routeProvider to load the content a bit more dynamically?

so for anchor tag #name1, when that view is displayed, I can pass "name1" into nameHolder as a variable to load some files with same name.

HTML

<a href="#name1"><span>name1</span></a>

JS

var nameHolder = [];
var sampleApp = angular.module('sampleApp', ['ngRoute']);

sampleApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/' + nameHolder, {
        templateUrl: 'templates/individkcd.html',
        controller: 'individ',
        nameofuser: nameHolder
    }).
      when('/', {
        templateUrl: 'templates/home.html'
    });
}]);


sampleApp.controller('individ', function($scope, $route) {

    $scope.img =  $route.current.nameHolder;


});

Thanks for any info.

UPDATED: Solution at new thread.

angular js - passing a variable into $routeProvider

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to add the parameter to your $routeProvider template:

sampleApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/' + nameHolder, {
        templateUrl: 'templates/individkcd/:nameHolder',
        controller: 'individ'
    }).
      when('/', {
        templateUrl: 'templates/home.html'
    });
}]);

Then in your target controller use $routeParams:

sampleApp.controller('individ', function($scope, $routeParams) {

    $scope.img =  $routeParams.nameHolder;


});

From the $routeProvider docs linked above:

path can contain named groups starting with a colon: e.g. :name. All characters up to the next slash are matched and stored in $routeParams under the given name when the route matches


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...