0

インデックス ページから別のビュー テンプレートにルーティングしようとしています。最初に、メイン インデックス ページのリストが読み込まれ、main.htmlが ng-view に読み込まれ、テキスト コンテンツが表示されます。「MainCtrl」からのデータは適切にブロードキャストされ、正常に動作します。ここで混乱しているのは、リストのアイテムがクリックされると、コンテンツ テンプレート ( content.html ) にルーティングされますが、リストを最初にクリックしたときにバインドされた値がコンテンツに表示されないことです。しかし、2 回目のクリックの後、MainCtrlからブロードキャストされたバインドされた値が表示され始めます。

<body ng-app="myApp">

  <div ng-controller="MainCtrl">
     <ul ng-repeat="value in msg" ng-click="setSelectedValue(value)">
         <li>
           <a href='#/content'>{{ value }}</a>
         </li>
     </ul>
   </div>

  <div ng-view=""></div>

main.html:

<p>Select from the list.</p>

content.html:

//loads the selected item from the list on index page
<h3>Selected: {{ message }}</h3> 

angular
  .module('myApp', ['ngRoute'])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/content', {
         controller: 'ContentCtrl',
        templateUrl: 'views/content.html'

      })
      .otherwise({
        redirectTo: '/'
      });
  })

.factory('myService', function($http, $rootScope){      
        var sharedService ={};
        sharedService.message = '';

        sharedService.prepforBroadcast = function(value){
            this.message = value;
            this.broadcastItem();
        };

        sharedService.broadcastItem = function(){
            $rootScope.$broadcast ('handleBroadcast');
        };

        return {
            sharedService: sharedService    
         };
})

  .controller('MainCtrl', function ($scope, myService) {
    $scope.msg = data; //this will be json data 
    $scope.selectedValue;

    $scope.setSelectedValue = function(value){
        $scope.selectedValue = value;
        myService.sharedService.prepforBroadcast(value);

    }
  })

.controller('ContentCtrl', function ($scope, myService) {
    $scope.$on('handleBroadcast', function(){
        $scope.message = myService.sharedService.message;
    })
});

テンプレートがすぐに読み込まれる場合でも、最初のクリックでデータをバインドしない理由が正確にはわかりません。どんな助けや考えも大歓迎です。しばらく頭をかく。

4

2 に答える 2

0

ng-repeatとはng-clickli にある必要があります。

 <ul>
     <li ng-repeat="value in msg" ng-click="setSelectedValue(value)">
       <a href='#/content'>{{ value }}</a>
     </li>
 </ul>
于 2014-09-21T05:37:50.200 に答える