Dem*_*nko 4 javascript model-view-controller angularjs angularjs-directive angularjs-scope
我正在尝试在使用指令单击表单中的按钮后在模板中显示注释
HTML:
<h2>Comments</h2>
<ul class="comments_list">
<li ng-repeat="com in comments" ng-cloak>{{com.name}} wrote<div class="message">{{com.text}}</div></li>
</ul>
<div class="add_comment" ng-show="posts.length > 0">
<input type="text" class="form-control" ng-model="addComm.name" placeholder="Your name">
<textarea class="form-control" ng-model="addComm.text" placeholder="Enter message"></textarea>
<button class="btn btn-success" add-comment ng-model="addComm">Add</button>
</div>
Run Code Online (Sandbox Code Playgroud)
和JS:
app.directive('addComment', function() {
return {
restrict: 'A',
require: 'ngModel',
priority: 1,
link: function ($scope, element, attrs, ngModel) {
element.on("click", function(event){
event.preventDefault();
console.log(ngModel.$modelValue);
$scope.comments.push(angular.copy(ngModel.$modelValue));
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
但在HTML中单击"添加"后,我的视图没有更新.如果我刷新页面(我正在使用ngStorage) - 新注释将出现在列表中,但不会在单击"添加"按钮后出现.
它正在发生,因为您正在更改javascript单击处理程序中的$ scope变量的值.试试这个:
app.directive('addComment', function() {
return {
restrict: 'A',
require: 'ngModel',
priority: 1,
link: function ($scope, element, attrs, ngModel) {
element.on("click", function(event){
event.preventDefault();
console.log(ngModel.$modelValue);
$scope.$apply(function() {
$scope.comments.push(angular.copy(ngModel.$modelValue));
});
});
}
}
});
Run Code Online (Sandbox Code Playgroud)