我创建了一个自定义指令,它接受来自控制器的数据。它的作用是,在调用时,它会动态创建单选按钮的布局。 我想要做的是在单击单选按钮时显示所选数据。
我的控制器:
var app = angular.module('myApp', []);
app.controller('DataController', ['$scope', function($scope){
$scope.gender = {
label: "Gender",
required:true,
valueList: [
{ text: "Male", value: "male" },
{ text:"Female", value:"female" }
]
};
$scope.my = { sel: '' };
}]);
指令:
app.directive('appleRadio', function(){
return {
restrict: 'E',
require: 'ngModel',
scope: {
fieldOptions: '=options',
fieldModel: '=ngModel',
fieldName: '@fieldName',
},
controller: ['$scope', function($scope) {
}],
link: function(scope, element, attribute, controller) {
element.on('click', function(){
// test1: assign the selected value to $scope.my.sel in controller
scope.$parent.my.sel = scope.selected;
// test2: assign the selected value to ng-model in template
scope.fieldModel = scope.selected;
console.log(scope.selected);
});
},
template: '<label style="text-indent: 1em;" ng-repeat="option in fieldOptions.valueList"> <input type="radio" name="option-{{option.value}}"'+
'id="option-{{value}}" ng-model="$parent.selected" value="{{option.value}}">{{option.text}}'+
'</label>'
};
});
在index.html中:
<div ng-controller="DataController">
<apple-radio field-label="Gender" field-name="oGend" options="gender" ng-model="selectedOption"></apple-radio>
<br/>You Selected (via ng-model): {{selectedOption}}<br/>
You Selected (via controller): {{my.sel}}<br/>
</div>
这里是plunker链接:
答案 0 :(得分:1)
每当您对角度方法/事件之外的角度上下文进行更改时,您需要调用scope.$apply()
。
因此,在onClick处理程序的末尾,调用scope。$ apply()。