Lahib
Lahib

Reputation: 1365

Angular code not seeing controller and items

I am new to angular an trying to create and MVC project with angular. I have create an about.js file and this is the code inside it:

(function () {
    var app = angular.module('myApp', []);

    app.controller('TecknologiesController', function () {
        this.text = tech;
    });
    var tech = {
        name: 'Progamming',
        csharp: 'C#',
        asp: 'ASP .NET',
        xaml:'XAML',
        java: 'java',
        sql: 'SQL',
        plsql: 'PL/SQL',
        xml: 'XML',
        webs: 'Web Services'
    }
})();

I have added my script tags to the body of _layout.cshtml file like so:

<body>
    <script type="text/javascript" src="angular.min.js"></script>
    <script type="text/javascript" src="About.js"></script>

In my About.cshtml file i have this code to show one of the tech items in my about.js this is my code:

<div ng-app="myApp" ng-controller="TecknologiesController as tech">
    <div>{{tech.text.name}}</div>
</div>

But this is not working for me. it prints out the {{tech.text.name}} as text. Am i adding the script tags wrong or what? it is working fine here in fiddle: http://jsfiddle.net/pYh89/1/

Upvotes: 0

Views: 38

Answers (1)

Dave Bush
Dave Bush

Reputation: 2402

ng-controller="TecknologiesController as tech" makes 'tech' point to this.

I think what you want is:

(function () {
    var app = angular.module('myApp', []);

    app.controller('TecknologiesController', function () {
        this.tech = tech;
    });
    var tech = {
        name: 'Progamming',
        csharp: 'C#',
        asp: 'ASP .NET',
        xaml:'XAML',
        java: 'java',
        sql: 'SQL',
        plsql: 'PL/SQL',
        xml: 'XML',
        webs: 'Web Services'
    }
})();

And your HTML:

<div>{{tech.tech.name}}</div>

It really would be better if var tech = ... was declared and assigned before you use it.

You could also to this:

(function () {
    var app = angular.module('myApp', []);

    app.controller('TecknologiesController', function () {
        var tech = this;
        tech.name = 'Programming;
        tech.csharp = 'C#';
        // etc ...
    });
})();

which would allow you to access name more directly

<div>{{tech.name}}</div>

But since I don't know what you are really trying to do, that's the best I can answer at this point.

You main issue, I think is that you don't understand that this is what tech points to.

Upvotes: 1

Related Questions