修改指令的模板,使其访问与创建它的指令相同的作用域
Modify the template of a directive to access the same scope as the directive that created it
这里是AngularJs新手。首先,我可能做错了,所以请随意提出任何关于我的方法的建议。我想做的是有一个应用模板的元素指令。下面是初始指令myDirective。
directives.directive('myDirective', [function() {
var template = "<button type='button' class='btn btn-default' my-other-directive={{model}}>CLICK ME</button>";
function link(scope, element, attrs) {
};
return {
restrict: 'E',
link: link,
scope: {
model: '@'
},
template: template
};
}]);
在我的HTML中是这样引用的
<my-Directive model="ThisVaries"></my-Directive>
的"myOtherDirective"
directives.directive('myOtherDirective', [function() {
function link(scope, element, attrs) {
var attr = attrs.myOtherDirective;
element.bind('click', function() {
scope.$parent.$parent.data.contact[attr].splice(0, 1); // need the index of the item
});
};
return {
restrict: 'A',
link: link
};
}]);
基本上,这是一个联系人表单,用户将在其中单击按钮,它将从控制器scope.data.contact[variable][index]中删除项目。我能够获得传入的attr
变量来访问祖父母的作用域。数据变量,但当我点击按钮时,模型不更新。
我昨天才开始使用指令,我很确定这不是正确的方法。任何帮助都是有帮助的。
controller.js文件中的控制器包含$作用域。Data属性,它是整个HTML部分的控制器。
Angular通过在$digest周期内执行所有内容来实现其神奇的双向绑定,但是当事件发生在Angular已经执行的事情之外时(例如由element.bind('click'
触发的click
事件),你需要通过与scope.$apply
一起运行它来手动指示它返回到$digest周期内。
应用于你的例子:
directives.directive('myOtherDirective', [function() {
function link(scope, element, attrs) {
var attr = attrs.myOtherDirective;
element.bind('click', function() {
scope.$apply(function() {
scope.$parent.$parent.data.contact[attr].splice({0, 1}); // need the index of the item
})
});
};
return {
restrict: 'A',
link: link
};
}]);
相关文章:
- AngularJs指令,该指令创建内部有数据对象的新指令
- 两个指令创建新的继承的和隔离的作用域-元素得到哪个
- 如何为通过ng-view指令或ng-controller指令创建的每个新作用域设置侦听器
- 如何使用自定义指令创建 angularjs 动态模板
- 香草JS到角度指令;创建使用角度指令的 DOM 元素
- 角度指令创建html 5视频播放器
- 在 AngularJs 中使用指令创建读取更多/更少切换
- 为Angular指令创建的元素创建名称
- 如何在Angularjs中使用按钮点击指令创建选择选项
- 如何为Angularjs指令创建仅限输入的参数
- 更新ng repeat using指令创建的图像
- Angular指令创建——使用多个模板
- 如何用angularjs指令创建可重用的组件
- Angular指令创建画布并下载为图像
- AngularJS -指令链接函数不会在元素从另一个指令创建后触发
- 指令创建[下载]按钮
- 无法在单击单个按钮时删除使用指令创建的表的选定行
- AngularJs:如何对指令创建的动态元素应用Form验证
- 如何将不同的ng模型值分配给从一个指令创建的多个输入字段?
- 指令创建flash警报