【问题标题】:template not displaying binded data after routed, on first click - AngularJS模板在路由后不显示绑定数据,第一次点击 - AngularJS
【发布时间】:2014-09-21 05:08:04
【问题描述】:

尝试从索引页面路由到不同的视图模板。最初,主索引页面上的列表被加载,main.html 被加载到 ng-view 中,显示它的文本内容。来自“MainCtrl”的数据已正确广播并且工作正常。现在,令人困惑的是,当单击列表中的项目时,它会被路由到内容模板(content.html),但内容不显示绑定的值第一次点击列表。但是,在第二次单击后,它开始显示从 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;
    })
});

不确定在第一次点击时没有绑定数据的确切原因是什么,即使模板立即加载也是如此。任何帮助或想法将不胜感激。挠了挠头。

【问题讨论】:

  • 可能是因为`ng-click="setSelectedValue(value)"`

标签: angularjs angularjs-service route-provider ngroute angular-template


【解决方案1】:
<ul ng-repeat="value in msg" ng-click="setSelectedValue(value)">

检查没有ng-click="setSelectedValue(value)" 部分。似乎您的点击将由setSelectedValue(value) 函数处理

【讨论】:

  • 如果没有 ng-click,从列表中选择的值甚至不会被广播到服务。
  • 第一次点击时,content.html 加载正常,但在ContentCtrl 中它永远不会进入$scope.$on,而是读取$scope.$on 之外的所有内容。只有在第二次点击后,它才会进入$scope.$on。所以,无法弄清楚它为什么会这样。
【解决方案2】:

ng-repeatng-click 应该在 li 上。

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

【讨论】:

  • 试过了,没有任何区别。
猜你喜欢
  • 2014-06-04
  • 2017-05-17
  • 2017-03-17
  • 2019-04-13
  • 2016-01-29
  • 2015-09-02
  • 2011-08-13
  • 1970-01-01
  • 2021-11-07
相关资源
最近更新 更多