Domanda

I have some trouble with my directive. I load the data about a user in which role it is. I want to do that when loading controller is selected which is attached to the user's role. I try to initialize with scope.SelectedValue, but something don't work, or i need to do in another way.

var app = angular.module('app');

app.directive('roleDirective', ['userRepository', function (userRepository) {
    return {
        restrict: 'E',
        template: '<select id="roles" ng-model="SelectedValue" ng-change="Change()">' +
                        '<option ng-repeat="role in Roles" value="{{role.RoleId}}">{{role.RoleName}}' +
                        '</option>' +
                  '</select>',
             link: function (scope, elem, attrs) {

            if (scope.User.webpages_Roles.length > 0) {
                scope.SelectedValue = scope.User.webpages_Roles[0].RoleId;
            }

        }
    }
}]);
È stato utile?

Soluzione

Really, this kind of stuff seems to belongs in a factory and controller. The link function in the directive is mainly for DOM manipulation, but you are doing model manipulation and making your life more difficult.

But to answer your question you are having trouble because of timing of the link function versus the compiling of the template.

To hackishly fix your problem try this:

  if (scope.User.webpages_Roles.length > 0) {
      // The true param at the end forces a scope.$apply() / digest cycle
      $timeout(function () {
          scope.SelectedValue = scope.User.webpages_Roles[0].RoleId;
      }, 100, true);
  }

Ideally you should have your "User" model in a .factory that has some convience methods on it like this plunkr

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top