2017-06-14 71 views
0

我在视图中有一个按钮,它完全在视图中处理,因为它只是一个简单的开关,用ng-show指令切换元素的视图。我希望能够从自己的指令中切换视图。

这里的什么我试图做一个示例代码:

<div> 
<button ng-click="ToChange=true"> 
<my-directive ng-show="ToChange"></my-directive> 
</div> 

    .directive('myDirective', function() { 
    return { 
    ... 
    controller: function ($scope) { 
     $scope.whenClickedThis = $scope.ToChange=false ??? 
    }, 
    ... 
    }; 
}); 

回答

2

在你的角度指令,你可以有访问父范围或隔离范围。如果你打算使用父范围,然后

angular.module('app') 
.controller('mainController', function($scope){ 
    $scope.ToChange = false; 
}) 
.directive('myDirective', function(){ 
    return { 
     restrict: 'E', 
     controller: function($scope){ 
      //You can access $scope.ToChange here 
     }), 
     link : function($scope, $element, $attribute){ 
      //You can access $scope.ToChange here 
     } 
    } 
}); 

<div ng-controller="mainController"> 
    <button ng-click="ToChange=true"> 
    <my-directive ng-show="ToChange"></my-directive> 
</div> 

如果您打算为您创造指令的分离范围,

angular.module('app') 
.controller('mainController', function($scope){ 
    $scope.ToChange = false; 
}) 
.directive('myDirective', function(){ 
    return { 
     restrict: 'E', 
     scope : { 
      change : '=' 
     }, 
     controller: function($scope){ 
      //Now you can access $scope.change from here 
     }), 
     link : function($scope, $element, $attribute){ 
      //Now you can access $scope.change from here 
     } 
    } 
}); 

<div ng-controller="mainController"> 
    <button ng-click="ToChange=true"> 
    <my-directive change="ToChange"></my-directive> 
</div> 

你可以在哟创建一个手表乌尔指令,如果你想找出任何改变你的变量

$scope.$watch('change', function(oldValue, newValue) { 
    //Do something here; 
}); 

了解更多关于角范围here

0
var app = angular.module("test",[]); 

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

    return { 

     restrict: "EA", 

     scope: true, 

     link: function(scope,elem,attr){ 

      // code goes here ... 
     } 

    } 

}); 
+0

虽然代码只回答可以解决问题,但它始终是最好提供代码劝 –

+0

感谢的一些说明,会考虑下一次。如果我已经有这个范围了,该怎么办?范围:{ ngLead:'=', ngShowLead:'=', }, –

+0

这个答案缺乏解释,我很难看到人们怎么能理解这个问题是如何解决的,特别是新手指导的人,请详细说明 –

0

您可以直接访问您的指令父范围变量。

angular.module('your-module').directive('myDirective', function() { 
    return { 
    controller: function ($scope) { 
     $scope.ToChange = !$scope.ToChange; 
    } 
    }; 
}); 
相关问题