我有一个带有倒计时的小脚本,通过directive
创建,如果$scope
内的controller
值为true
,则会启动该脚本。这是html
代码:
<countdown from="3" start-if="{{startCountdown}}"></countdown>
其次是directive
:
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
并解决此问题吗?提前感谢您的回复!
答案 0 :(得分:2)
<强>予。子范围指令。
您没有创建隔离范围,因此最简单的解决方案是在控制器中删除from
属性和init 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
});
}
}
});
&#13;
<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>
&#13;
<强> II。隔离范围指令
您也可以使用隔离范围执行相同的操作,它需要通过=
(双向绑定)传递变量。例如:
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
}
}
});
&#13;
<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>
&#13;
答案 1 :(得分:1)
您可以使用 $ broadcast 来实现相同的代码。
controller: function($scope, $element, $attrs, $rootScope) {
$scope.count = $attrs.from;
function countdown(){
var intervalID = $interval(function() {
$rootScope.$broadcast('counterVal',{
countVal:$scope.count
});
if ($scope.count > 0) {
$scope.count--;
} else {
$interval.cancel(intervalID);
}
}, 1000);
}
$attrs.$observe('startIf', function(value) {
if (value) {
countdown();
}
});
}
请找到工作的plunker here.