简体   繁体   中英

angular directive variable not available in parent scope

I am currently stuck on hopefully a simple problem:

I have a controller.js

app.controller('WizardCtrl', function ($scope) {
  $scope.send = function() {
    console.log($scope.isPasswordChanged)
  }
});

My view.html

isPasswordChanged: {{ isPasswordChanged }} <br>
<update-password-field is-changed="isPasswordChanged"></update-password-field>
<button ng-click="send()"></button>

My directive.js

app.directive('updatePasswordField', function () {
  return {
    restrict: 'E',
    scope: {
      isChanged: "="
    },
    templateUrl: "password-field-directive.html",
    link: function (scope) {
        // some magic to set isChanged value to true of false 
    }
  }
});

So in my view.html I can see the changes of "isPasswordChanged", to it is somehow in my $scope, but if I console.log($scope) the "isPasswordChanged" is not present.

Why and how to make it present?

I think you need to include the $scope in your controller's function(). In other words:

app.controller('WizardCtrl', ['$scope', function ($scope) {

Otherwise I don't believe it will work.

Turned out it is a problem with probably my structure.

I changed

is-confirmed="isPasswordConfirmed"

to

is-confirmed="ui.isPasswordConfirmed"

"ui" is an empty object I defined in my $scope.

And its working. I tried a stand alone example

http://plnkr.co/edit/bkMZTEWgkrmVfxqiYCcB?p=preview

But it is working without this changes, it also might be a mismatch with angular version.

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