簡體   English   中英

如何創建綁定到變量的AngularJS指令?

[英]How to create an AngularJS directive that binds to a variable?

我想構建一個顯示datepicker文本框的指令,即使用JQuery UI的datepicker的常規文本框,所以當用戶點擊它們時,會打開一個datepicker框讓他們選擇日期等。

我想以某種方式將此指令綁定到我的作用域上的屬性。 例如,如果它是普通的文本框,並且我執行了ng-model='myDate'那么如果用戶輸入新的日期,則會更新$scope.myDate 以同樣的方式,我想從指令綁定此字段,因此當用戶選擇日期時,它會更新其綁定的范圍屬性。

問題是,我想用這樣的東西顯示指令:

<datepicker name='something' value='2013-07-20' model='myProperty' />

並將指令替換為<input type="text" />等。所以我不能使用ng-model

我怎樣才能將model屬性綁定到指令,以便在用戶更改時更新?

看看這是不是你想要的:

HTML

<div ng-app="app" ng-controller="Ctrl">
    <foo model="property"></foo>
    <input type="text" ng-model="property">
</div>

使用Javascript

angular.module('app', [])
    .directive('foo', function() {
        return {
            restrict: 'E',
            replace: true,
            scope: { model: '=' },
            template: '<input type="text" ng-model="model">'        
        };
    })
    .controller('Ctrl', function($scope) {
       $scope.property = 'Foobar'; 
    });

的jsfiddle

為了使用ng-model而不是model ,您需要將輸入包裝在容器標記中。 這是另一個說明它的jsFiddle腳本。

最后, Angular UI Bootstrap中有一個日期選擇器控件。 也許它已經做了你需要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM