[英]AngularJS Directive with no Template and Sharing the updates from parent scope
我有一個非常簡單的要求,在這個指令中,我要把對指令的更改下推到ng-repeat內 ,以便更新UI。 意思是我想要在鏈接函數中使用Contact(不僅是字符串引用實際對象)的值,這樣我就可以呈現UI並在父ng-repeat中的contact更改時更改UI。
我已經創建了一個非常簡單的版本 ,可以實現。 它有一個聯系人列表(在Mark對此鏈接的幫助下進行研究后,我知道ng-repeat創建了自己的作用域,因此我添加了一個稱為deep的對象,該對象不是原始對象),我正在努力進行排序。 我也曾嘗試使用其他可能的選項。 我不想用ng-show / ng-class的東西在指令中粘貼模板,因為業務邏輯非常棘手,因此使用鏈接功能更容易做到。 我敢肯定這與范圍和/或$ observe有關,但我不知道如何進行排序。 還要注意,這是我想要實現的簡單版本。 我實際上想要該對象的值來呈現我的UI。
我的小提琴示例當您單擊“更新名稱”時,您會看到外部重復內容沒有內部更新。
<div>
<div ng-controller="ContactsCtrl">
<ul>
<li ng-repeat="contact in contacts">
<div zippy="contact">a</div>
</li>
</ul>
<br />
<p>Here we repeat the contacts to ensure bindings work:</p>
<br />
<ul>
<li ng-repeat="contact in contacts">
{{contact.name}} : {{contact.deep}}
</li>
</ul>
</div>
</div>
var app = angular.module( 'myApp', [] );
app.controller('ContactsCtrl', function ( $scope ) {
$scope.contacts = [
{ name: 'Sharon',deep:{A:"a"}},
{ name: 'Steve',deep:{A:"b"}},
{ name: 'Scott',deep:{A:"c"}}
];
$scope.primitiveTest=function(c){c.name=c.name+c.name; }
$scope.objectTest=function(c){c.deep={A:c.deep.A+c.deep.A}; }
});
app.directive('zippy', ['$compile', function ($compile){
return {
restrict: 'A',
link: function(scope, element, attrs) {
/*scope.$watch(attrs.zippy, function(newValue, oldValue){
alert('asd');
});
attrs.$observe('deep',function(val){ alert('asd'); });*/
scope.$watch(attrs['zippy'],
function (ideaNode) {
var html = [];
html.push('<hr/><div class="clearfix" id="vote-icons" ng-click="primitiveTest('+attrs['zippy']+');" >Update Name </div> - <div class="clearfix" id="vote-icons" ng-click="objectTest('+attrs['zippy']+');">UpdateObject');
html.push('</div>');
html.push(JSON.stringify(ideaNode));
element.html(html.join(''));
$compile(element.contents())(scope);
}
);
}
}
}]);
如果采用以下方法,則可以在指令中刪除$ watch。
您應該使用對象插值html.push("{{" + attrs['zippy'] + "}}");
如果要對模型進行插值和更新,請使用序列化的純文本字符串。
app.directive('zippy', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var html = [];
html.push('<hr/><div class="clearfix" id="vote-icons" ng-click="primitiveTest(' + attrs['zippy'] + ');" >Update Name </div> - <div class="clearfix" id="vote-icons" ng-click="objectTest(' + attrs['zippy'] + ');">UpdateObject');
html.push('</div>');
html.push("{{" + attrs['zippy'] + "}}");
element.html(html.join(''));
$compile(element.contents())(scope);
}
}
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.