我尝试在angular指令中创建一个函数,该指令只应更改一个对象值。
将变量直接传递给函数不会起作用:
var that = new Object();
但是传递父对象会:
<body ng-controller="MainCtrl">
<div test ng-click="changeVar(variable.value)">{{ variable.value }}</div>
</body>
app.directive('test', [function(){
return {
link: function(scope, elem, attrs) {
scope.variable = {
value : "bla"
};
scope.changeVar = function(value) {
value = "hhuhu"
};
}
}
}]);
为什么我必须将父Object传递给函数来覆盖该值,并且不能直接传递该值来覆盖它?我错过了什么吗?
答案 0 :(得分:3)
我认为你在这里缺少的是angularjs中范围的概念以及它们是如何传递的。
当您声明您的指令时:
app.directive('parent', [function(){
return {
controller: function($scope) {
$scope.variable = {};
// init
$scope.variable.value = "foo";
}
}
}]);
app.directive('child', [function(){
return {
controller: function($scope) {
// here you are directly using the parent's scope
// so you can access $scope.variable directly
// without sending it in the function
$scope.changeObj = function(replacement) {
$scope.variable.value = replacement ;
};
}
}
}]);
你基本上是在告诉angular使用父作用域作为作用域,因为你没有为你的指令定义一个特殊的作用域。
(顺便说一句,这种行动:
scope.changeObj = function(obj) {
obj.value = "hhuhu"
};
不应该在链接函数中,而是在控制器中,它看起来像我的控制器逻辑:)
您可以做的第二件事是通过参数将变量发送到子范围,如下所示:
app.directive('parent', [function(){
return {
controller: function($scope) {
$scope.variable = {};
// init
$scope.variable.value = "foo";
}
}
}]);
app.directive('child', [function(){
return {
scope:{myVariable: '='},
controller: function($scope) {
// here you are directly using the child's scope
// but since you have defined double binding,
// changing this in the child will also update the parent
$scope.changeObj = function(replacement) {
$scope.myVariable.value = replacement ;
};
}
}
}]);
<body ng-controller="MainCtrl">
<div test my-variable="variable" ng-click="changeObj('some text')">{{ variable.value }}</div>
</body>
我希望现在很清楚