Home  >  Q&A  >  body text

angular.js - Angular中的directive指令是否能接受object类型的赋值?

我想写一个list
利用directive来写一个item
这个item要根据赋予的不同的值产生相应变化 但目前我只知道简单的数据赋值
例如

.directive('al-item', function() {
    return {
        restrict: 'EA',
        template: '

<p>'
                 +'</p>

',
        replace: true,
        controller: function($scope, $element, $attrs, $transclude) {
            //这里根据a、b、c 三者的值 进一步修饰al-item
        }
    };
})

<al-item a='' b='' c=''>

我希望的形式 更像是

<al-item object=''>

这样提供一个object数据
al-item就能实现我预定的样子
请问这可以实现吗?

曾经蜡笔没有小新曾经蜡笔没有小新2714 days ago601

reply all(3)I'll reply

  • 阿神

    阿神2017-05-15 16:54:52

    You can look at the scope part of the instruction to solve your questions.

    Approximately:

    html<p ng-controller="cc">
    <al-item object="obj"></al-item>
    </p>
    
    jsangular.module('xx', [])
    .controller('cc', ['$scope', function($scope) {
        $scope.obj = {a:'a', b:'b', 'c':'c'}
    }])
    .directive('alItem', function() {
        return {
            restrict: 'EA',
            template: '<p>'+'</p>',
            replace: true,
            transclude: true,
            scope: {
                object: "="
            },
            controller: function($scope, $element, $attrs, $transclude) {
                //scope.object 这里就可以判断了
            }
        };
    })
    

    Probably like this. For details, you can read the official documentation

    reply
    0
  • PHP中文网

    PHP中文网2017-05-15 16:54:52

    Directive scope itself supports three modes
    1. "=" any object
    2. "&" The external method is passed into the directive and called internally
    3. "@" string

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-15 16:54:52

    The object in HTML is also an attrs. Attrs has been transferred into the function. You can use attrs to call object directly.

    reply
    0
  • Cancelreply