我的界面
<ion-view title = "{{roomName}}" style = "height:90%;margin-top: 45px " ng-init = "init()">
<ion-pane>
<ion-content zooming = "true" class = "no-header">
<ion-list>
<ion-item class="item item-input-inset">
<label class="item-input-wrapper">
<input type="text" placeholder="Your Message To Send" ng-model = "myMessage">
</label>
<button class="button button-small" ng-click = "sendMyMessage()">
发送
</button>
</ion-item>
</ion-list>
</ion-content>
</ion-pane>
<ion-pane style = "margin-top: 55px">
<ion-content zooming = "true" class = "no-header" style = "margin-bottom: 50px">
<ion-list>
<ion-item class = "item item-avatar-left my-item"
collection-repeat = "message in messages"
collection-item-width="'100%'"
collection-item-height="75">
<img ng-src="{{message.user.avatarUrl}}">
<h2>{{message.user.name}}:</h2>
<p>{{message.content}}</p>
</ion-item>
</ion-list>
</ion-content>
</ion-pane>
</ion-view>
我的controller
atMoon.controller('roomCtrl',['$scope','myService', function ($scope, myService) {
$scope.sendMyMessage = function () {
console.log($scope.myMessage)
myService.sendMyMessage($scope, $scope.myMessage)
}
$scope.init = function () {
myService.getMessages($scope);
}
}])
打印的$scope.myMessage一直是undefine,如果我在controller中写上$scope.myMessage = "xxxx"能再界面中显示,所以数据只能从模型到视图,不能从视图到模型,求大神解答万分感谢
我怀疑你这是被 scope 的原型继承坑了
像
ion-content
这些指令都是有各自的 scope 的,然后你在视图里写上ng-model="myMessage"
,其实你在输入框填入的内容是放到了ion-item
的 scope 上了,而你的roomCtrl
的 scope 里的myMessage
依旧是undefined
;而当你在控制器里给myMessage
赋值完了以后,由于ion-item
的 scope 上还没有myMessage
属性,所以就会从原型链上找,进而找到了roomCtrl
的 scope 上的myMessage
。这是我常用的解决方案: