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

前端之家收集整理的这篇文章主要介绍了angularjs – Angular指令:混合属性数据和ngModel前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有幸建立了共享范围的指令,以及隔离范围的指令,但我无法找到正确的方法来做到这两点.

< 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));
        }
    }
}]);

两种选择似乎都很好.

猜你在找的Angularjs相关文章