Fer*_*ndo 26 angularjs angularjs-directive angularjs-scope
我需要在指令内的回调中修改根范围属性.但该指令位于由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>
Run Code Online (Sandbox Code Playgroud)
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';
}
Run Code Online (Sandbox Code Playgroud)
小提琴:http://jsfiddle.net/nJ7FQ/
我的目标是能够在Selected区域中显示"New value".我怎样才能完成我想做的事情?我究竟做错了什么?
此外,因为我正在尝试制作一个组件.有没有办法做同样但具有孤立的范围?
sha*_*ain 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';
}
Run Code Online (Sandbox Code Playgroud)
和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>
Run Code Online (Sandbox Code Playgroud)
更新了小提琴,使用属性中您对该属性的原始读取:http: //jsfiddle.net/nJ7FQ/4/
sto*_*ofl 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' };
}
Run Code Online (Sandbox Code Playgroud)
这样,您想要更改的范围值也可以是selected.foo示例中的对象属性.此外,我删除了scope参数并告诉指令始终使用父作用域.最后,我将click处理程序包装到$apply回调中(例如,请参见此处).当然,更好的是使用ngClick而不是element.bind().
| 归档时间: |
|
| 查看次数: |
57144 次 |
| 最近记录: |