转换指令以使用隔离范围
Convert a directive to use isolated scope
我创建了一个简单的指令,但目前我没有设置任何范围。但是我希望该指令使用隔离范围,以便我可以轻松地重用它。
这是我的 html 指令被称为 "select-time":
<div class="menuHour after" select-time><div class="menuHour-panel before"><span class="menuHour-panel-title" ng-click="changeToBefore()">Before 12h</span></div>
我让示例保持简短,所以它在这里所做的唯一一件事就是将 class "menuHour after" 更改为 "menuHour before"。
它使用一种方法 "changeToBefore()" 来做到这一点。
这是我的指令:
angular.module("tiki").directive("selectTime", function(newTiki){
return {
restrict:"A",
controller:function($scope, $element, $attrs){
$scope.changeToBefore = function(){
var menuHour = document.querySelector(".menuHour")
menuHour.classList.remove("after")
menuHour.classList.add("before")
}
}
}
})
如何将其更改为独立作用域指令?
谢谢,
你可以用 scope: {}
定义一个 isolated scope:
我也会使用 $element 而不是再次获取元素!
angular.module("tiki").directive("selectTime", function(newTiki){
return {
restrict:"A",
scope: {},
templateUrl: '/path/to/directive.html',
controller:function($scope, $element, $attrs){
$scope.changeToBefore = function(){
$element.removeClass("after")
$element.addClass("before")
}
}
}
})
我创建了一个简单的指令,但目前我没有设置任何范围。但是我希望该指令使用隔离范围,以便我可以轻松地重用它。
这是我的 html 指令被称为 "select-time":
<div class="menuHour after" select-time><div class="menuHour-panel before"><span class="menuHour-panel-title" ng-click="changeToBefore()">Before 12h</span></div>
我让示例保持简短,所以它在这里所做的唯一一件事就是将 class "menuHour after" 更改为 "menuHour before"。
它使用一种方法 "changeToBefore()" 来做到这一点。
这是我的指令:
angular.module("tiki").directive("selectTime", function(newTiki){
return {
restrict:"A",
controller:function($scope, $element, $attrs){
$scope.changeToBefore = function(){
var menuHour = document.querySelector(".menuHour")
menuHour.classList.remove("after")
menuHour.classList.add("before")
}
}
}
})
如何将其更改为独立作用域指令?
谢谢,
你可以用 scope: {}
定义一个 isolated scope:
我也会使用 $element 而不是再次获取元素!
angular.module("tiki").directive("selectTime", function(newTiki){
return {
restrict:"A",
scope: {},
templateUrl: '/path/to/directive.html',
controller:function($scope, $element, $attrs){
$scope.changeToBefore = function(){
$element.removeClass("after")
$element.addClass("before")
}
}
}
})