gpt4 book ai didi

javascript - 将范围值从指令传递到 Controller - AngularJS

转载 作者:行者123 更新时间:2023-11-28 18:23:16 25 4
gpt4 key购买 nike

我有一个带有倒计时的小脚本,通过指令创建,如果controller内的$scope值是 true。这是 html 代码:

<countdown from="3" start-if="{{startCountdown}}"></countdown>

后跟指令的代码:

app.directive('countdown', function ($interval) {
return {
restrict: 'E',
template: '{{count}}',
controller: function($scope, $element, $attrs) {
$scope.count = $attrs.from;

function countdown(){
var intervalID = $interval(function() {
if ($scope.count > 0) {
$scope.count--;
} else {
$interval.cancel(intervalID);
}
}, 1000);
}

$attrs.$observe('startIf', function(value) {
if (value) {
countdown();
}
});
}
}
});

倒计时工作正常,但在 Controller 内部,如果$scope.count === 0,应该有一个alert() > 但它不起作用。

这是一个Plnkr与完整的代码。您知道如何将 $scope.count 的值传递给 controller 并解决这个问题吗?预先感谢您的回复!

最佳答案

我。子范围指令。

您没有创建隔离作用域,因此最简单的解决方案是删除 from 属性并在 Controller 中初始化 count 作用域变量。所以:

//controller code
//init variable
$scope.count=3;

//directive code
//manipulate variable
$scope.count--;

没有独立作用域(子作用域)的指令示例:

var app=angular.module("app",[]);
app.controller("controller",function($scope,$timeout){

$scope.count=2;
$scope.start=false;//start countdown flag


$scope.$watch("count",function(val){

console.log("Count is changed to:"+val);

});

});

app.directive("myDirective",function($timeout){

return{
restrict:"E",
template:"{{count}}",
link:function(scope){

scope.count++;//example change

$timeout(function() { scope.count++; },2000);//example change

scope.$watch("start",function(){

//here we watch changes in start scope variable
//here start countdown

});

}
}


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="controller">
<my-directive></my-directive>
</div>

二.隔离范围指令

您也可以使用隔离作用域执行相同的操作,它需要通过 = (双向绑定(bind)) 传递变量。示例:

    var app=angular.module("app",[]);
app.controller("controller",function($scope){

$scope.count=2;

$scope.$watch("count",function(val){

console.log("Count is changed to:"+val);

});

});

app.directive("myDirective",function($timeout){

return{
restrict:"E",
scope:{
count:"="//pass variable to isolated scope
},
template:"{{count}}",
link:function(scope){

scope.count++;//example change

$timeout(function() { scope.count++; },2000);//example change

}
}


});
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="controller">
<my-directive count="count" ></my-directive>
</div>

关于javascript - 将范围值从指令传递到 Controller - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39573551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com