为什么传递给指令的函数不更新作用域变量?
Why does a function passed to a directive not update a scope variable?
在此AngularJS代码中:
http://jsfiddle.net/edwardtanguay/xfbgjun5/8/
我有一个作用域函数 addCustomer()
,它不会更新作用域变量 score
:
.controller('mainController', function ($scope) {
$scope.customers = ['First','Second','Third'];
$scope.score = 'sdfkj';
$scope.addCustomer = function() {
$scope.score = 'this does not work';
console.log('but it obviously gets here');
}
$scope.changeIt = function() {
$scope.score = 'this works';
}
...
})
我传入函数 addCustomer()
作为 add
:
return {
restrict: 'A',
scope: {
datasource: '=',
add: '&'
},
link: link
};
然后在我的指令中调用它:
function addItem() {
scope.add();
items.push('new customer');
render();
}
为什么作用域函数addCustomer()
不更新作用域变量score
?
查看您的 fiddle 您的问题在这里:
element.on('click', function(event) {
if(event.target.id === 'addItem') {
addItem();
event.preventDefault();
}
});
通过执行 element.on,您将在 angular 中组织自己的活动。这行不通,您也需要这样做:
element.on('click', function(event) {
if(event.target.id === 'addItem') {
addItem();
event.preventDefault();
scope.$apply();
}
});
这是因为 'click' 发生在 angular 之外,如果您以这种方式构建它。您还应该研究如何构建指令,因为这不是您构建它的方式(使用 html 变量然后添加它)。您的指令代码中不应有任何 html(在特定情况下除外)。
在此AngularJS代码中:
http://jsfiddle.net/edwardtanguay/xfbgjun5/8/
我有一个作用域函数 addCustomer()
,它不会更新作用域变量 score
:
.controller('mainController', function ($scope) {
$scope.customers = ['First','Second','Third'];
$scope.score = 'sdfkj';
$scope.addCustomer = function() {
$scope.score = 'this does not work';
console.log('but it obviously gets here');
}
$scope.changeIt = function() {
$scope.score = 'this works';
}
...
})
我传入函数 addCustomer()
作为 add
:
return {
restrict: 'A',
scope: {
datasource: '=',
add: '&'
},
link: link
};
然后在我的指令中调用它:
function addItem() {
scope.add();
items.push('new customer');
render();
}
为什么作用域函数addCustomer()
不更新作用域变量score
?
查看您的 fiddle 您的问题在这里:
element.on('click', function(event) {
if(event.target.id === 'addItem') {
addItem();
event.preventDefault();
}
});
通过执行 element.on,您将在 angular 中组织自己的活动。这行不通,您也需要这样做:
element.on('click', function(event) {
if(event.target.id === 'addItem') {
addItem();
event.preventDefault();
scope.$apply();
}
});
这是因为 'click' 发生在 angular 之外,如果您以这种方式构建它。您还应该研究如何构建指令,因为这不是您构建它的方式(使用 html 变量然后添加它)。您的指令代码中不应有任何 html(在特定情况下除外)。