3

特定のURLが使用されている場合、angularjsのルーティングを使用してjavascript関数を呼び出そうとしています。

次のコードは、期待される結果を提供していません。

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

app.config(function($routeProvider) {
    $routeProvider.when('/link1', {
         controller: 'PageController'
   })
   .when('/link2', {
        controller: 'PageController'
   })
   .otherwise({ 
        controller: 'PageController'
   });
});

app.controller('PageController', function($scope, $routeParams) {
   alert('1');
});

これらのalert(1);URL のいずれかが要求された場合、 は呼び出されません...

多分誰かがこれを解決する方法を知っていますか?

4

3 に答える 3

1

There is no way to associate the routing with a specific action in the controller. The routing in the AngularJS is not like the routing in other web frameworks to route to specific action of request. Instead, the routing in the AngularJS is primarily relating to handle the page flow and the controller defines the scope of the page.

However, if you put the alert in the controller like that, it should be triggered when the page is loaded. You need to check whether the URL you used is correct or not. To test, you can simply put $location.url('/link1') in your code.

于 2013-08-27T15:36:16.600 に答える
0

コントローラーが特定のルートで使用されている場合は、コントローラー内でその関数を呼び出すことができます。ルートが変更され、コントローラーが呼び出されると実行されます。

このhttp://plnkr.co/edit/qUZ5Q7nKCRAS8dFvjRIgで link1 をクリックすると警告が表示されます。

コードが期待どおりに機能しない理由はよくわかりませんが、同様のアプリのセットアップを作成したところ、機能しました。

var app = angular.module('myApp',[]).

config(['$routeProvider',function($routeProvider) {
      $routeProvider.
          when('/', {
            controller: 'PageController',
            template: '<br><br>this is page #/<br> {{data}}',
          }).
          when('/link1', {
            controller: 'SpecificPageController',
            template: '<br><br>this is page #/link1<br> {{data}}' 
          }).
          when('/link2', { 
            controller: 'PageController',
            template: '<br><br>this is page #/link2<br> {{data}}' 
          }).
          otherwise({redirectTo:'/'});
    }]).

controller('PageController', function($scope, $routeParams) {
    $scope.data = 'hello world';
}).

controller('SpecificPageController', function($scope, $routeParams) {

    $scope.data = 'hello specific';
    alert(1);    
});

SpecificPageController がルートに割り当てられ、そのルートが開かれるたびに、アラート関数が実行されます。

于 2013-08-27T15:35:48.673 に答える