2016-02-27 41 views
1

我有一些問題,從我的形式把我的輸入

存在的一些代碼行下面,說明由錯誤檢測 我也重新它CodePen

$scope.dish.comments.push(Object.keys{rating: $scope.comment.rating, comment: $scope.comment.comment, author: $scope.comment.author, date: $scope.comment.date}); 

所以,每次我提出我的形式,我總是得到這樣的通知,並在控制檯

TypeError: Cannot read property 'comments' of undefined

我甲肝在另一個控制器中聲明$scope.dish = dish;,所以我希望我可以從另一個控制器訪問它,但它不起作用,因爲我希望

+0

你有'$ scope.dish'不確定,請嘗試使用它之前對其進行初始化...'$ scope.dish = {}' – harishr

+0

控制器範圍並不全球,你可能需要從API調用JSON或從文件或定義insame控制器 – Prasad

回答

1

您試圖在兩個控制器之間共享數據,我建議您使用服務工廠DishDetails然後在兩個控制器上注入依賴關係,然後修改數據,將反映到每個控制器。

下面介紹如何使用工廠服務共享數據。

function factory() { 
 
    var service = { 
 
    set: setData, 
 
    get: getData 
 
    }; 
 

 
    service.records = [{ 
 
    FirstName: 'FirstName', 
 
    LastName: 'LastName', 
 
    Age: '21' 
 
    }]; 
 
    return service; 
 

 

 
    function getData() { 
 
    return service.records; 
 
    } 
 

 
    function setData(data) { 
 
    service.records.push(data); 
 
    } 
 
} 
 

 
angular 
 
    .module('mainApp', []) 
 

 
.factory('dataRecords', factory) 
 

 
.controller('AddDataController', function($scope, dataRecords) { 
 
    $scope.AddRecord = function() { 
 
    var data = { 
 
     FirstName: $scope.FirstName, 
 
     LastName: $scope.LastName, 
 
     Age: $scope.Age 
 
    } 
 
    dataRecords.set(data) 
 
    } 
 
}) 
 

 
.controller('ViewDataController', function($scope, dataRecords) { 
 
    $scope.records = dataRecords.get(); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<link data-require="bootstrap-css" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" /> 
 

 
<div ng-app="mainApp"> 
 
    <div ng-controller="AddDataController"> 
 
    First Name: 
 
    <input type="text" ng-model="FirstName" name="FirstName" placeholder="Enter First Name" required>Last Name: 
 
    <input type="text" ng-model="LastName" placeholder="Enter Last Name">Age: 
 
    <input type="number" ng-model="Age"> 
 
    <button type="button" ng-click="AddRecord()">ADD</botton> 
 
    </div> 
 
    <div ng-controller="ViewDataController" class="container"> 
 

 
    <h3>Record List Controller</h3> 
 
    <table class="table"> 
 
     <tr> 
 
     <th>FirstName</th> 
 
     <th>LastName</th> 
 
     <th>Age</th> 
 
     </tr> 
 
     <tr ng-repeat="person in records"> 
 
     <td>{{ person.FirstName }}</td> 
 
     <td>{{ person.LastName }}</td> 
 
     <td>{{ person.Age }}</td> 
 
     </tr> 
 
    </table> 
 
    </div> 
 
</div>

+0

您可以通過給服務工廠提供一個簡短的邏輯來幫助我嗎? – Lyriene

0

您的NG-控制器= 「DishDetailController」 添加到父行內容div中的其他控制器將繼承$ scope.dish。因此:

<div class="row row-content" ng-controller="DishDetailController"> 
     <div class="col-xs-9 col-xs-offset-1" > 
     ... 
     </div> 
     <div class="col-xs-9 col-xs-offset-1" ng-controller="DishCommentController"> 
     ... 
     </div> 
</div> 
相關問題