AngularJS : Directive Isolated Scope Undefined

萝らか妹 提交于 2019-12-10 16:16:17

问题


I am writing a directive with an isolate scope with a two-way binding in AngularJS. However, I cannot seem to get the two-way binding to work. No matter what I do, the populate property on the isolate scope is always undefined (although the property does exist) instead of being the value it's supposed to be bound to.

HTML:

<html>
  <body ng-app="MyApp">
    <div ng-controller="MyController">
      {{data.dataProp}} <!-- demonstrates that data.dataProp is defined -->
      <scope-fail data-source="data.dataProp"></scope-fail>
    </div>
  </body>
</html>

JS:

angular.module("MyApp", [])
.controller('MyController', function ($scope) {
  $scope.data = {
    dataProp: 'Some Data'
  }
})
.directive('scopeFail', function ($window) {
  return {
    restrict: 'E',
    scope: {
      populate: '=dataSource'
    },
    template: '<div>Value: {{populate}}</div>',
    link: function (scope, element, attrs) {
      console.log('Scope property:', scope.populate); //prints Scope property: undefined
    }
  };
})

CodePen with above code: CodePen link

So why doesn't the CodePen show "Value: Some Data"? What I think is supposed to happen is that populate binds to the value of data-source on the custom element which is data.dataProp on the controller scope which is Some Data.

Where am I going wrong with this/how can I get the isolate scope to have a two-way binding with the data-source attribute?

Thank you so much


回答1:


Either change populate: '=dataSource' to populate: '=source' or add an extra data- attribute prefix to data-source. AngularJS automatically strips the data- attribute to allow for valid html5 scoped attributes.




回答2:


You have the wrong syntax. It should be this

.directive('scopeFail', function ($window) {
  return {
    restrict: 'E',
    scope: {
      dataSource: '='
    },
    template: '<div>Value: {{scope.dataSource}}</div>',
    link: function (scope, element, attrs) {
      console.log('Scope property:', scope.dataSource); //prints Scope property: undefined
    }
  };
})

The scope properties are passed in as attributes by the attribute name, and you define the data binding as two way, evaluate, or read only.

EDIT

csbarnes answer will also work since dataSource: '=' is just shorthand for dataSource: '=dataSource' but it makes readability and debugging more difficult IMO. I find it easier to keep the attribute names and scope properties the same. But to each their own.



来源:https://stackoverflow.com/questions/31393812/angularjs-directive-isolated-scope-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!