我需要在指令内的回调中修改根范围属性。但该指令位于由switch指令创建的内部作用域中。
HTML
<div ng-app="app" ng-controller='AppController'>
<p>Selected: {{ selected }}</p>
<div ng-switch on="selected">
<div ng-switch-default>
<p>Item: {{ selected }}</p>
<custom-tag selected-item="selected" />
</div>
<div ng-switch-when="New value">
<p>Worked</p>
</div>
</div>
</div>
的JavaScript
angular.module('app', [])
.directive("customTag", [function () {
return {
restrict: "E",
replace: true,
template: "<input type='button' value='Click me' />",
link: function (scope, element, attrs) {
element.bind('click', function () {
scope[attrs.selectedItem] = "New value";
scope.$apply();
});
}
};
}]);
function AppController($scope) {
$scope.selected = 'Old value';
}
小提琴:http://jsfiddle.net/nJ7FQ/
我的目标是能够在Selected区域中显示“New value”。 我怎样才能完成我想做的事情?我做错了什么?
此外,因为我正在尝试制作一个组件。有没有办法做同样的事情,但有一个孤立的范围?
答案 0 :(得分:20)
我更新了小提琴,基本上不得不去父母那里获得正确的“选定”变量,还使用了isolate scope =来获取传入的值与内部模型之间的双向绑定。
angular.module('app', [])
.directive("customTag", [function () {
return {
restrict: "E",
replace: true,
template: "<input type='button' value='Click me' />",
scope: {model:'='},
link: function (scope, element, attrs) {
element.bind('click', function () {
scope.model[attrs.selectedItem] = "New value";
scope.$apply();
});
}
};
}]);
function AppController($scope) {
$scope.selected = 'Old value';
}
和HTML
<div ng-app="app" ng-controller='AppController'>
<p>Selected: {{ selected }}</p>
<div ng-switch on="selected">
<div ng-switch-default>
<p>Item: {{ selected }}</p>
<custom-tag selected-item="selected" model="$parent" />
</div>
<div ng-switch-when="New value">
<p>Worked</p>
</div>
</div>
</div>
更新了小提琴,以便从属性中使用您对该属性的原始读取: http://jsfiddle.net/nJ7FQ/4/
答案 1 :(得分:15)
我改进了jsfiddle:
angular.module('app', [])
.directive("customTag", ['$parse', function ($parse) {
return {
restrict: "E",
replace: true,
template: "<input type='button' value='Click me' />",
link: function (scope, element, attrs) {
element.bind('click', function () {
scope.$apply(function () {
$parse(attrs.selectedItem).assign(scope.$parent, "New value");
});
});
}
};
}]);
function AppController($scope) {
$scope.selected = { 'foo': 'Old value' };
}
这样,您要更改的范围值也可以是示例中的selected.foo
之类的对象属性。此外,我删除了scope参数并告诉指令始终使用父作用域。最后,我将点击处理程序包装到$apply
回调中(例如,请参阅here)。当然,更好的是使用ngClick
而不是element.bind()
。