javascript - angularjs指令
本文介绍了javascript - angularjs指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
diretive.js:
function myInput() {
return {
restrict: 'E',
scope: false,
templateUrl:
'<div class="{{_init.colNum}}">
<div class="form-group">
<label class="control-label">{{_init.name}}</label>
<input class="form-control" type="text" size="16" ng-model="yy">
</div>
</div>',
controller: function ($scope) {
}
}
}
html:
<my-input my-model="xx"></my-input>
问题是:
我想要在myInput的指令上,在封装一个属性指令比如myModel,myModel里面的xx去替代(或者叫映射),myInput里面的yy这个ng-model,有什么好的办法。怎么去写myModel这个指令啊
解决方案
使用scope 来读取这个变量
scope: {
yy: '@myModel',
},
scope: false 继承父级的scope
scope: true 不继承,全新的scope
-
scope: { xx: '@xx ', yy: '=yy', zz: '&zz' } 从attribute读取相应的值,
这里的有3个格式
-
@ 读取变量
$scope.abc = '123'; <div my-model="abc" /> yy => abc 等于父级的变量,abc变了,这个一起变
-
= 读取值
$scope.abc = '123'; <div my-model="{{abc}}" /> yy => 123 获取值,和abc没有关系
-
& 一般用于调用函数
$scope.click = function() {}; <div my-model="click" /> yy => 父级的函数
-
如果 scope: false,可以这样 (万不得已的不要这样用)
注入:$compile $templateRequest $sce
function myInput($compile, $templateRequest, $sce) {
return {
...
...
scope: false,
link: function(scope, element, attrs) {
scope.yy = attrs.myModel;
//需要读取远程模板的
var templateUrl = $sce.getTrustedResourceUrl('path/to/template.html');
$templateRequest(templateUrl).then(function(template) {
element.html(template);
$compile(element.contents())(scope);
}, function() {
// An error has occurred
});
//无需读取的
element.html('<div>..模板内容..</div>');
$compile(element.contents())(scope);
}
}
}
这篇关于javascript - angularjs指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文