简体   繁体   中英

Angular directive own scope

I have the following directive

<preload loaded="false" ng-if="!loaded"></preload>

return {

            restrict: 'E',
            templateUrl: 'template.html',
            scope: {
                loaded: '='
            },


            link: function(scope, element, attrs) {        
                //scope.loaded = true
                //hide directive
            }

        }

Outside any controller.

My question is, can I change the loaded to true inside the link function and the directive will dissapear?

Do you mean change the value via some action like clicking a button? If so:

I think you could toggle that value in the same way you would any other value. A fourth parameter that can be passed is the controller.

link: function(scope, element, attrs, ctrl) {
  scope.loaded = true;
  scope.toggle = function() {
    scope.loaded = !scope.loaded;
  };
}

And then you can assign the scope.toggle to a button. Or do you mean just change the value when the link function is run?

EDIT

Here's a quick plunkr demonstrating what you mean written for angular 1.5:

https://plnkr.co/edit/6nj4N6LdGULv7vX4EUqs?p=preview

EDIT 2 Lines 13-20 of my plunkr:

angular
    .module('app')
    .controller('PreloadCtrl',PreloadCtrl);

  function PreloadCtrl() {
    var vm = this;
    vm.loaded = false;
  }

This basically defines a controller called PreloadCtrl and passes it a function which acts as the controller. This is the same as doing this, which is probably what you're used to:

.controller('PreloadCtrl', function () {//Controller stuff})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM