2014-12-04 97 views
1

我創建了一個Angular js指令,通過ng-repeat循環,如果用戶選擇任何這些單選按鈕,它應該提醒當前的ng-model值。AngularJs指令獲取單選按鈕的ng-model值更改

但它不工作。請幫忙。

var someapp = angular.module('someapp', []); 
 

 
someapp.controller('someappCtrl', function($scope, $http) { 
 
    //... 
 

 
}).directive('checkthemChoice', function() { 
 
    return { 
 
    restrict: 'A', 
 
    template: '<label ng-repeat="choice in choices" for="{{ choice }}"><input type="radio" ng-checked="$first" name="selecttable" ng-model="radioSelected" value="{{ choice }}" id="{{ choice }}"> {{ choice }}</label>', 
 
    link: function(scope, element, attrs) { 
 
     scope.choices = ['organization', 'user']; 
 

 
     element.on('change', function() { 
 
     //this selected the parent DIV checkthem 
 
     //but I want select the radio input inside LABEL 
 
     }); 
 

 
     scope.$watch('radioSelected', function(val) { 
 
     //this doesnt work 
 
     alert(val); 
 
     }); 
 
    } 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="someapp" ng-controller="someappCtrl"> 
 

 
    <div class="checkthem" checkthem-Choice=""></div> 
 

 
</div>

+0

我一直在看這幾分鐘現在我發現令我奇怪的是,手錶觸發前值radioSelected甚至存在? – Blackunknown 2014-12-04 10:30:53

回答

4

這工作。

radioSelected需要是對象的屬性(例如,測試)。這裏給出的解釋https://github.com/angular/angular.js/wiki/Understanding-Scopes

另外,我有一個測試undefined在手錶,以避免第一次警報負載。

var someapp = angular.module('someapp', []); 
 

 
someapp.controller('someappCtrl', function($scope, $http) { 
 
    //... 
 

 
}).directive('checkthemChoice', function() { 
 
    return { 
 
    restrict: 'A', 
 
    template: '<label ng-repeat="choice in choices" for="{{ choice }}"><input type="radio" ng-checked="$first" name="selecttable" ng-model="test.radioSelected" value="{{ choice }}" id="{{ choice }}"> {{ choice }}</label>', 
 
    link: function(scope, element, attrs) { 
 
     scope.choices = ['organization', 'user']; 
 
     scope.test = {}; 
 
    
 
     element.on('change', function() { 
 
     //this selected the parent DIV checkthem 
 
     //but I want select the radio input inside LABEL 
 
     }); 
 

 
     scope.$watch('test.radioSelected', function(val) { 
 
     if (val !== undefined) alert(val); 
 
     }); 
 
    } 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="someapp" ng-controller="someappCtrl"> 
 

 
    <div class="checkthem" checkthem-Choice=""></div> 
 
</div>

+0

也謝謝,我試過了。它也起作用。 '

' 並在無線電上我引用它回到父'' – STEEL 2014-12-04 10:46:45

+0

@STEEL有趣。這似乎不是正確的做法,但我不能給你一個明確的理由。我建議我的解決方案,因爲它有點乾淨。 – 2014-12-04 10:52:52

+0

當然,這是乾淨的;) – STEEL 2014-12-04 11:35:36