gpt4 book ai didi

angularjs - 在 AngularJS 中更新模型时如何触发指令?

转载 作者:行者123 更新时间:2023-12-02 19:25:34 24 4
gpt4 key购买 nike

我找到了一个很好的解决方案,用于在 Angular JS 中内联编辑内容,该解决方案是通过在模型上运行 ng-repeat 创建的:https://stackoverflow.com/a/16739227/2228613

为了扩展该解决方案,我在页面上添加了一个按钮,该按钮具有 ng-click 指令,如下所示:

<button ng-click="addCategory()" class="btn btn-large btn-primary" type="button">
<i class="icon-white icon-plus"></i> Add Category
</button>

addCategory 函数在我的 Controller 中定义:

$scope.addCategory = function(){
var newCategory = {id:0, name:"Category Name"};
$scope.categories.unshift(newCategory);
}

这里的目标是允许用户添加新记录,并在 View 更新为新行后自动触发内联编辑指令。如何以这种方式触发内联编辑指令?

最佳答案

我使用的一种技术是使用 bool 值更改值并使用 $watch在需要触发的指令内。

myApp.directive('myDirective', function () {
return function (scope, element, attr) {
scope.$watch('someValue', function (val) {
if (val)
// allow edit
else
// hide edit
});
}
});

然后在你的 Controller 中设置$scope.someValue = true;在您的 ng-click 中单击按钮。

骗子:http://plnkr.co/edit/aK0HDY?p=preview

<小时/>

更新

我对上面的答案做了进一步的阐述。我已经做了一些更符合你所追求的东西。

这是它的代码:http://plnkr.co/edit/y7iZpb?p=preview

这是新指令:

  .directive('editCar', function ($compile) {
return {
restrict: 'E',
link: function (scope, element, attr) {
var template = '<span class="car-edit">'+
'<input type="text" ng-model="car.name" />' +
'<button ng-click="someValue = false" class="btn btn-primary">Save</button></span>';
scope.$watch('someValue', function (val) {
if (val) {
$(element).html(template).show();
$compile($('.car-edit'))(scope);
}
else
$(element).hide();
});
}
}
})

它取代了 <edit-car></edit-car>具有上述模板的元素。保存按钮将值添加到名为 editedCars 的数组中。我留下了一些虚拟代码,用于使用 $http.post() 提交整个内容。

关于angularjs - 在 AngularJS 中更新模型时如何触发指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17138868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com