angularjs指令
高洛峰
高洛峰 2016-11-12 11:54:19
0
1
711
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这个指令啊

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

membalas semua(1)
三叔

使用scope 来读取这个变量

    scope: {
        yy: '@myModel',
    },

scope: false 继承父级的scope

scope: true 不继承,全新的scope

scope: { xx: '@xx ', yy: '=yy', zz: '&zz' } 从attribute读取相应的值,

这里的有3个格式

@ 读取变量

$scope.abc = '123';
yy => abc 等于父级的变量,abc变了,这个一起变

= 读取值

$scope.abc = '123';
yy => 123 获取值,和abc没有关系

& 一般用于调用函数

$scope.click = function() {};
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('
..模板内容..
');             $compile(element.contents())(scope);         }     } }


Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan