2

我想创建一个指令并在我的控制器中使用参数:

<body ng-app="tstApp">
    <navigationbar tst="hello">
    </navigationbar>
</body>

为此,我创建了一个指令及其控制器:

navigationBar = {};
navigationBar.directives = {};
navigationBar.controllers = {};

navigationBar.directives.navigationbar = function () {
    return {
        restrict: 'E',
        scope: {
            t1: '@tst',
            t2: '=tst',
            t3: '&tst'
        },
        templateUrl: "common/navigation_bar/navigation_bar.tpl.html",
        controller: "NavigationBarController"
    }
};

navigationBar.controllers.NavigationBarController = function ($scope, Api) {
    console.log($scope);
    console.log($scope.t1);
    console.log($scope.t2);
    console.log($scope.t3);
};

testApp.directive(navigationBar.directives);
testApp.controller(navigationBar.controllers);

在控制台中我得到了这个:

Scope {$id: "003", $$childTail: null, $$childHead: null, $$prevSibling: null, $$nextSibling: null…}
$$asyncQueue: Array[0]
$$childHead: Child
$$childTail: Child
$$destroyed: false
$$isolateBindings: Object
$$listeners: Object
$$nextSibling: Child
$$phase: null
$$prevSibling: null
$$watchers: Array[9]
$id: "003"
$parent: Scope
$root: Scope
nav: Object
t1: "hello"
t2: undefined
t3: function (locals) {
this: Scope
__proto__: Object

和:

undefined navigation_bar.js:33
undefined navigation_bar.js:34
function (locals) {
                  return parentGet(parentScope, locals);
                }

我想了解为什么console.log($scope.t1); 不显示范围内的值-> t1:“你好”

谢谢您的帮助,

胡里奥

添加信息:

如果我将 templateUrl 替换为:

template: "Scope Id: {{$id }}, t1: {{ t1 }}"

我有:

Scope Id: 003, t1: hello

如果我像这样在控制器中放置一些跟踪:

console.log('Scope Id: ' + $scope.$id +  ', t1: ' + $scope.t1);

我有:

Scope Id: 003, t1: undefined 

所以范围是相同的并且是共享的。但是为什么我无法达到控制器中的 t1 值。我应该评估它吗?

4

2 回答 2

0

我明白了。

1. 为什么未定义。

我认为这个值是未定义的,因为在控制器的构造过程中绑定没有完成。

2.如何获取价值

由于属性是通过@传递的,我们需要定义一个观察者来观察绑定。为此,我添加了链接属性:

    link: function($scope, $element, $attr) {
        $attr.$observe('tst', function(value){
            console.log('value', value)
            $scope.nav.selection = value
        }
        );
    }

我希望这是最好的方法。

于 2013-08-19T20:43:30.287 回答
0

范围仅将@隔离范围的值设置为普通属性值,该值始终为字符串。它不以任何方式评估。

您可以在指令定义对象部分下的AngularJS 指令文档中阅读有关范围对象的更多信息。

于 2013-08-19T18:59:12.863 回答