AngularJS directive with default options

前端 未结 3 653
说谎
说谎 2020-12-12 12:38

I\'m just starting with angularjs, and am working on converting a few old JQuery plugins to Angular directives. I\'d like to define a set of default options for my (element)

3条回答
  •  囚心锁ツ
    2020-12-12 12:50

    Use the =? flag for the property in the scope block of the directive.

    angular.module('myApp',[])
      .directive('myDirective', function(){
        return {
          template: 'hello {{name}}',
          scope: {
            // use the =? to denote the property as optional
            name: '=?'
          },
          controller: function($scope){
            // check if it was defined.  If not - set a default
            $scope.name = angular.isDefined($scope.name) ? $scope.name : 'default name';
          }
        }
      });
    

提交回复
热议问题