Angularjs ng更改在自定义指令中不起作用
我有以下自定义指令:Angularjs ng更改在自定义指令中不起作用,angularjs,Angularjs,我有以下自定义指令: app.directive('stream', ['BitrateCalculator', function(BitrateCalculator) { return { restrict: 'E', transclude: true, templateUrl: 'directives/stream.html', controller: function() { this.
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 ... -->
圣安东尼奥:
H.264
MJPEG
MPEG-4
所有这些代码以前都在控制器中,HTML只在一个文件中。我现在正试图将重复的HTML(因为它是一个带有几乎相同字段的选项卡式页面)提取到AngularJS中的自定义指令中
在此重构之前,一切正常,每次字段更改时都会调用函数calculate()
,但在此之后,ngChange
不再工作,尽管双向数据绑定仍然通过ngModel
工作
这是怎么可能的?我需要做什么才能使
ngChange
再次工作?我不喜欢在指令中包含控制器,您可以尝试将逻辑移动到链接函数,类似这样:
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
});
}
}
}]);
请将此作为参考您应该将作用域注入控制器,请参见此处的演示
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'
}
}
]);