Javascript 带有指令的AngularJs范围引用
我试图用Angular编写一个非常简单的三星计分系统,但是在使用数组中的项目引用时,我遇到了指令作用域的问题 出于测试目的,我的标记如下所示:Javascript 带有指令的AngularJs范围引用,javascript,angularjs,Javascript,Angularjs,我试图用Angular编写一个非常简单的三星计分系统,但是在使用数组中的项目引用时,我遇到了指令作用域的问题 出于测试目的,我的标记如下所示: <div id="ref"> <span>Reference to item 1: </span> <item-score ng-model="selected.score"></item-score> </div> <div ng-repeat="item
<div id="ref">
<span>Reference to item 1: </span>
<item-score ng-model="selected.score"></item-score>
</div>
<div ng-repeat="item in items track by $index">
<div class="row">
<span>{{item.name}}:</span>
<item-score ng-model="item.score"></item-score>
<item-score ng-model="item.score"></item-score>
</div>
</div>
提及项目1:
{{item.name}}:
我的JavaScript已经简化,但做了同样的事情:
var App = angular.module('testApp', []);
App.controller('MainCtrl', ['$scope', function ($scope) {
$scope.items = [
{ id: 1, score: 1, name: 'Item 1' },
{ id: 2, score: 2, name: 'Item 2' },
{ id: 3, score: 1, name: 'Item 3' }
];
$scope.selected = $scope.items[1];
}]);
App.directive('itemScore', function () {
return {
restrict: 'E',
require: '?ngModel',
replace: true,
template: '<div class="score"><i class="fa fa-star" ng-click="set($index+1)"' +
' ng-repeat="star in stars track by $index" ' +
'ng-class="{ yellow: star === true }"></i></div>',
link: function (scope, elm, attrs, ctrl) {
var num = 5;
scope.stars = new Array(num);
scope.set = function (score) {
if (ctrl.$viewValue === score) { score--; }
ctrl.$setViewValue(score);
};
function setStars () {
for (var i = 0; i < num; i += 1) {
scope.stars[i] = ((i+1) <= ctrl.$viewValue ? true : false);
}
}
ctrl.$render = function () {
setStars();
};
}
}
});
var-App=angular.module('testApp',[]);
App.controller('MainCtrl',['$scope',函数($scope){
$scope.items=[
{id:1,分数:1,名称:'Item 1'},
{id:2,分数:2,名称:'Item 2'},
{id:3,分数:1,名称:'Item 3'}
];
$scope.selected=$scope.items[1];
}]);
应用程序指令('itemScore',函数(){
返回{
限制:'E',
要求:“?ngModel”,
替换:正确,
模板:“”,
链接:函数(范围、elm、属性、ctrl){
var-num=5;
scope.stars=新数组(num);
scope.set=功能(分数){
如果(ctrl.$viewValue==score){score--;}
ctrl.$setViewValue(分数);
};
函数setStars(){
对于(变量i=0;i 范围星号[i]=((i+1)当您单击每行内的评分框时,两条指令都会正确更新,因为两条指令都在监视同一属性。因此,当其中一条指令更改启动次数时,另一条指令会收到该更改的通知并强制渲染。由于两条指令都位于相同的ng repeat
范围内,因此两个评分框都会被禁用重新渲染
尝试从ng repeat
中的行中删除其中一条指令,您会注意到它将不再正确更新
解决此问题的一种方法是在设置视图值后调用ctrl.$render()
。如下所示:
scope.set = function (score) {
if (ctrl.$viewValue === score) { score--; }
ctrl.$setViewValue(score);
ctrl.$render();
};
另一个选项是在范围
中定义ng模型
引用,并直接更新它
require : 'ngModel',
scope: {
ngModel: '=?'
}
然后:
scope.set = function (score) {
scope.ngModel = score;
};
我认为您应该改变方法,您应该使用这种方式绑定到指令并传递模型。谢谢,这样一个简单的解决方案。在我们的主应用程序中调用$render()似乎更可靠。