我有以下自定义指令:
app.directive('stream', ['BitrateCalculator', function(BitrateCalculator) {
return {
restrict: 'E',
transclude: true,
templateUrl: 'directives/stream.html',
controller: function() {
this.codec = '';
this.fps = 1;
this.resolution = '';
this.quality = 1;
this.bitrate = 16;
this.calculate = function() {
console.log('teste')
this.bitrate = BitrateCalculator.calculate(this.codec, this.resolution, this.quality, this.fps);
};
},
controllerAlias: 'ctrl'
}
}]);
及其模板:
<div class="row">
<div class="col-md-2">
<label for="encodingCamera">Compressão: </label>
<select name="encodingCamera" ng-model="ctrl.codec" ng-change="ctrl.calculate()" class="form-control" required>
<option value="h264" selected>H.264</option>
<option value="mjpeg">MJPEG</option>
<option value="mpeg4">MPEG-4</option>
</select>
<!-- <p ng-show="addCam.encodingCamera.$invalid && addCam.encodingCamera.$dirty">Selecione um valor</p> -->
</div>
<!-- ... more code ... -->
所有这些代码以前都在控制器中,而HTML只在一个文件中。我现在正在尝试将重复的HTML(因为它是一个包含大多数相同字段的标签页)提取到AngularJS中的自定义指令。
在重构之前,一切正常,每次字段更改时都会调用函数calculate()
,但在此之后,ngChange
不再有效,尽管双向数据绑定是仍在ngModel
工作。
这怎么可能,我需要做些什么才能使ngChange
再次工作?
答案 0 :(得分:0)
我不喜欢在指令中使用控制器,你可以尝试将你的逻辑移动到链接功能,如下所示:
app.directive('stream', ['BitrateCalculator', function(BitrateCalculator) {
return {
restrict: 'E',
transclude: true,
templateUrl: 'directives/stream.html',
link:function(scope, elem, attrs){
elem.bind('change', function(){
alert('element changed');
// call BitrateCalculator
});
}
}
}]);
看一下这个article作为参考
答案 1 :(得分:0)
您应该在控制器中注入示波器,请参阅此处演示http://plnkr.co/edit/iWAQx4IOmkz6lMQpgZHy?p=preview
app.directive('stream', ['BitrateCalculator',
function(BitrateCalculator) {
return {
restrict: 'E',
transclude: true,
scope:{},
templateUrl: 'stream.html',
controller: function($scope, BitrateCalculator) {
$scope.codec = '';
$scope.fps = 1;
$scope.resolution = 720;
$scope.quality = 1;
$scope.bitrate = 16;
$scope.calculate = function() {
console.log(BitrateCalculator);
console.log('teste')
$scope.bitrate = BitrateCalculator.calculate($scope.codec, $scope.resolution, $scope.quality, $scope.fps);
};
},
controllerAlias: 'ctrl'
}
}
]);