javascript - angularjs指令
天蓬老师
天蓬老师 2017-04-10 17:52:21
0
1
336
diretive.js:
 function myInput() {
  return {
    restrict: 'E',
    scope: false,
    templateUrl: 
    '<p class="{{_init.colNum}}">
      <p class="form-group">
        <label class="control-label">{{_init.name}}</label>
        <input  class="form-control" type="text" size="16" ng-model="yy">
      </p>
    </p>',
    controller: function ($scope) {
    
    }
  }
}
html:
<my-input my-model="xx"></my-input>

问题是:
我想要在myInput的指令上,在封装一个属性指令比如myModel,myModel里面的xx去替代(或者叫映射),myInput里面的yy这个ng-model,有什么好的办法。怎么去写myModel这个指令啊

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全員に返信(1)
刘奇

使用scope 来读取这个变量

    scope: {
        yy: '@myModel',
    },
  • scope: false 继承父级的scope

  • scope: true 不继承,全新的scope

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

    这里的有3个格式

    • @ 读取变量

      $scope.abc = '123';
      <p my-model="abc" />
      
      yy => abc 等于父级的变量,abc变了,这个一起变
    • = 读取值

      $scope.abc = '123';
      <p my-model="{{abc}}" />
      
      yy => 123 获取值,和abc没有关系
    • & 一般用于调用函数

      $scope.click = function() {};
      <p 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('<p>..模板内容..</p>');
            $compile(element.contents())(scope);
        }
    }
}
いいねを押す +0
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!