加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – Angular指令:混合属性数据和ngModel

发布时间:2020-12-17 17:37:48 所属栏目:安全 来源:网络整理
导读:我有幸建立了共享范围的指令,以及隔离范围的指令,但我无法找到正确的方法来做到这两点. input type =“text”ng-model =“search”append-me terms =“myTerms” 我正在尝试像上面那样输入一个输入,然后在一个属性列表后面重复一个UL重复的UL.我有两个问题.
我有幸建立了共享范围的指令,以及隔离范围的指令,但我无法找到正确的方法来做到这两点.

< input type =“text”ng-model =“search”append-me terms =“myTerms”>

我正在尝试像上面那样输入一个输入,然后在一个属性列表后面重复一个UL重复的UL.我有两个问题.

1)如何正确连接共享的ng-model范围?

2)我对这个编译函数做错了什么?

http://jsfiddle.net/vEQ6W/1/

解决方法

将隔离范围与ngModel混合是一个记录在案的问题,请参阅 documentation中的隔离范围陷阱部分:

Isolated Scope Pitfall
Note that if you have a directive with an isolated scope,you cannot require ngModel since the model value will be looked up on the isolated scope rather than the outer scope. When the directive updates the model value,calling ngModel.$setViewValue() the property on the outer scope will not be updated. However you can get around this by using $parent.

利用这些知识和一些奇怪的范围实验,我有两个选项可以做你想做的事情:

(1)见fiddle它使用了如上所述的$parent方法.

<div ng-controller="MyCtrl">
  <div>
    <input ng-form type="text" ng-model="$parent.search" append-me terms="myTerms">
  </div>
  {{search}}
</div>

myApp.directive('appendMe',['$compile',function($compile) {
    return {
        restrict: 'A',scope: {terms: '='},link: function(scope,element,attributes) { // linking function
            console.log(scope.terms);
            var template = '<p>test</p>' + 
                '<ul><li ng-repeat="term in terms">{{term}}</li></ul>' +
                '<p>hm…</p>'
            element.after($compile(template)(scope));
        }
    }
}]);

(2)参见fiddle它不使用$parent,而是使用隔离范围来发布通过ngModel配置的搜索模型.

<div ng-controller="MyCtrl">
    <div>
        <input ng-form type="text" ng-model="search" append-me terms="myTerms">
    </div>
    {{search}}
</div>

myApp.directive('appendMe',scope: {terms: '=',search: '=ngModel'},attributes) { // linking function
            console.log(scope.terms);
            var template = '<p>test</p>' + 
                '<ul><li ng-repeat="term in terms">{{term}}</li></ul>' +
                '<p>hm…</p>'
            element.after($compile(template)(scope));
        }
    }
}]);

两种选择似乎都很好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读