gpt4 book ai didi

javascript - 使用新的 bindToController 语法时,双向绑定(bind)不起作用

转载 作者:行者123 更新时间:2023-11-28 07:12:24 25 4
gpt4 key购买 nike

我正在尝试在指令内绑定(bind)变量,并使用新的 Angular 1.4 bindToController 语法从指令中修改它。

HTML:

<body ng-app="mainModule" ng-controller="mainController">
<h2>{{boundVar}}</h2>
<my-directive ng-model="boundVar"></my-directive>

Javascript:

angular.module('directiveModule', []).directive('myDirective',
function()
{
var r =
{
scope: true,
bindToController: { value: '=ngModel' },
template: '<h2>The value is: {{ctrl.value}}</h2><br><button ng-click="ctrl.increment()">Increment</button>',
controllerAs: 'ctrl',
controller: function()
{
this.increment = function() { this.value++; };
}
};

return r;
});

angular.module('mainModule', ['directiveModule']).controller('mainController',
function($scope)
{
$scope.boundVar = 10;
});

首次加载页面时,您会看到变量“boundVar”已有效绑定(bind):

enter image description here

但是当您按下按钮时,只有内部变量发生变化,因此双向绑定(bind)似乎不起作用:

enter image description here

我错过了什么?

谢谢!

最佳答案

我相信这只是常见情况,如果您不使用“.”,双向绑定(bind)通常不会按预期工作。在你的绑定(bind)中。您不应该双向绑定(bind)到基元。即使有了新的 bindToController 功能,同样的原则仍然适用。

参见https://stackoverflow.com/a/18128502/246811以获得更好的解释。

关于javascript - 使用新的 bindToController 语法时,双向绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31166914/

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