0

私はAngularjsが初めてです。

私がする必要があるのは、ビューに使用しているパスを$routeProvider追加の JavaScript 関数に渡すことcurrentPath()です。以下はのテストコードですが、別のフレームワークにあるrouteProvider関数へのパスを渡す方法がわかりませんcurrentPath():

var demoApp = angular.module('demoApp',[]);

demoApp.config(function ($routeProvider) {      
    $routeProvider
        .when('/',
            {
                controller: 'SimpleController',
                templateUrl: 'Partials/View1.html'
            })
        .when('/view2',
            {
                controller: 'SimpleController',
                templateUrl: 'Partials/View2.html'
            })
        .otherwise({redirectTo: '/'});
    });
4

1 に答える 1

0

良い、

どこにパスが必要ですか?AngularJS は、(ほとんど) 依存性注入 (DI) のアイデアに基づいて構築されています。

そのため、そのルートで実行されているコントローラー関数内で現在アクティブなパスが必要な場合は、以下を参照してください$location

function SimpleController($scope, $location) {
  console.log($location.path()); //the current path

  //assign the path to the scope
  $scope.path = $location.path();
}

ここで何が起こるかというと、$location必要なときに を注入するということです。に属性を付与する$scopeことで、現在使用中のパーシャルでアクセスできます。詳細については、こちらのドキュメントをご覧ください。

編集:

おそらくオブジェクトの一部(つまり、フレームワーク)であるコントローラーで使用できる外部関数があるとします。それを呼び出しましょうA

var A;
A = {
  currentPath: function(path) {
    //do something with the path
  }
}

//as long as a is available in the scope surrodung your controller, this should work
function SimpleController($scope, $location) {
  $scope.$on("$locationChangeSuccess", function(newValue, oldValue) {
    //this will be triggered after a location has changed,
    //other event to be tried out can be:
    // * $routeChangeStart
    // * $routeChangeSuccess
    // * $locationChangeStart
    A.currentPath($location.path());
  });

  //call it once initially
  A.currentPath($location.path());
}
于 2013-10-07T17:46:56.033 に答える