...">

Scope of the external control object

With Angularjs, you can bind an event to a dom element like this:

<div ng-controller="SampleController">
    <a ng-click="showTheHiddenDiv()">Show the hidden div</a>

    <div ng-show="showHiddenDiv">
        hidden content
    </div>
</div>

My question is: is it possible to connect an event handler function similar to this from outside the controller?

<a ng-click="showTheHiddenDiv()">Show the hidden div</a>

<div ng-controller="SampleController">
    <div ng-show="showHiddenDiv">
        hidden content
    </div>
</div>

This does not work, I am wondering if there is a special way to access the function showTheHiddenDiv(). I know that I could just wrap everything in another container and do it with the controller area, but I am wondering if it is possible to do so.

Thank!

+4
source share
2 answers

. , (ng-click div). , .

showDiv :

<div ng-controller="SampleController">
    <a href="#" ng-click="showDiv = !showDiv">Show the hidden div</a>

    <div ng-show="showDiv">
        hidden content
    </div>
</div>

'showDiv', SampleController. ng-show div showDiv ( showDiv, SampleController), 'showDiv'.

[EDIT]

, .

, , SampleController, :

<a href="#" ng-click="showDiv = !showDiv">Show the hidden div</a>

<div ng-controller="SampleController">

    <div ng-show="showDiv">
        hidden content
    </div>
</div>

- . , . SampleController ( ), ( ). , - . , .

ng-show showDiv, (). "showDiv" - undefined, , angular, undefined false. , showDiv ! ShowDiv. scope 'showDiv', SampleController, - - .

showDiv , ng-show, "showDiv" (, ) , (div, ).

+3

.

 app.service('SharedService', function(){
   this.showHiddenDiv = false;
 });

app.directive('showDiv', function(SharedService){

  return {
    restrict: 'AC',
    link : function(scope, element, attr) {
       scope.showHiddenDiv = SharedService.showHiddenDiv;
       scope.toggleDiv = function(){
         SharedService.showHiddenDiv = SharedService.showHiddenDiv ? false : true;
       }
    }
  }
})

HTML:

<a ng-click="toggleDiv()" show-div>Show the hidden div</a>

<div ng-controller="SampleController">
    <div ng-show="showHiddenDiv" show-div>
        hidden content
    </div>
</div>

, , DOM, , angular !

0

Source: https://habr.com/ru/post/1545162/


All Articles