gpt4 book ai didi

javascript - 将更改应用于 angular.js 中由scope.$apply 获取的模型

转载 作者:行者123 更新时间:2023-11-28 20:22:37 24 4
gpt4 key购买 nike

我在 AngularJS 中有一个指令,可以像这样获取数组:

var current_element_list = scope.$apply($(this).attr('sortable-model'));

其余代码如下所示:

//in the controller
$scope.project.elements = [];

//in the html
<customDirective sortable-model='project.elements'>

我认为scope.$apply会返回对$scope.project.elements数组的引用,这样我在指令中所做的任何更改都会保留在该模型中。然而,情况似乎并非如此,因为我对数组所做的任何更改都不会保存。无论如何,我是否可以将通过 sortable-model 属性获得的更改保存回根范围中的数组?

最佳答案

如果您希望指令和 Controller 作用域之间进行双向绑定(bind),则应在定义指令时使用 scope 属性。

var app = angular.module("app", []);

app.controller("Ctrl", function ($scope) {
$scope.project = {
elements: [1, 2, 3]
};
});

app.directive("customDirective", function () {
return {
restrict: "E",
scope: {
sortableModel: "="
},
link: function (scope, element, attrs) {
// Access the controller's scope.project.elements here as scope.sortableModel
console.log(scope.sortableModel);

// Changes to scope.sortableModel will also affect the controller's scope.project.elements
scope.sortableModel.push(4);
}
};
});

查看working fiddle in action .

关于javascript - 将更改应用于 angular.js 中由scope.$apply 获取的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17979377/

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