我似乎无法理解 Angular 指令中的适当绑定(bind)。我有以下代码:
html
<div ng-app="choreApp">
<div ng-controller="ChoreCtrl">
<div ng-repeat='chore in Chores'>
<h2 announce clicky-thing='updateName({chore: chore})' style='color: {{chore.color}}'>{{chore.name}} <== chore </h2>
</div>
<hr />
<input type="text" ng-model='chore.name' />
<input type="text" ng-model='chore.color' />
<br />
<button ng-click='updateName({chore: chore})'>Update Name to {{Chore.name}}</button>
</div>
</div>
//JavaScript
var app = angular.module("choreApp", []);
app.controller("ChoreCtrl", function ($scope) {
$scope.Chores = [
{name: 'Dude', color: 'blue'},
{name: 'Guy', color: 'black'},
{name: 'Dudette', color: 'red'},
{name: 'Gal', color: 'orange'}
];
$scope.updateName = function (chore) {
alert('okay ' + chore.name);
};
});
app.directive("announce", function () {
return {
restrict: "A",
scope: {
clickyThing: '&'
},
link: function (scope, elem, attrs) {
elem.bind('click', function () {
scope.clickyThing({chore: chore});
});
}
};
});
JSFiddle在这里:http://jsfiddle.net/k8xYX/14/
有四个 h2,每个都绑定(bind)到自己的 chore
对象。我想要的是能够单击 h2 之一,将单个 chore
绑定(bind)到 Controller 的范围(并使用 chore
的模型数据填充输入) ,更新其中一个输入元素,单击“更新名称”按钮并使该模型数据更新单击的 h2。
最佳答案
这是更新的 fiddle :
更新指令:
app.directive("announce", function () {
return {
restrict: "A",
scope: {
clickyThing: '&',
chore: '='
},
link: function (scope, elem, attrs) {
var chore = scope.chore;
elem.bind('click', function () {
scope.clickyThing(chore);
});
}
};
});
解决的问题:
- You've declared an isolated scope for the announce directive, but haven't imported the 'chore' model into your isolated scope - yet you reference chore when you execute the clickyThing(). I've changed it so that your directive imports the 'chore' model.
- You use { chore: chore } as the model passed to your click handlers - this is not necessary. I've changed this so that it passes the model directly.
- Within the updateName() method, its being called from outside the Angular context, so I've wrapped the assignment of chore in an $apply block. This ensures that a $digest is triggered after the execution of the code.
我同意 Kevin 的观点,你可能应该使用 ng-click 代替。
关于javascript - AngularJs:在指令之间共享模型数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24681638/